1

OOP (有益な使用法)のように、ショッピング カードのアイテムの請求書を作成する場合、Bill オブジェクトをバスケットの handleInvoice() 関数に渡します (すべて PHP で記述されています)。

class Basket {
    // -- other code 

    public function handleInvoice( Bill $invoice ) {
        $invoice->chargeFor( $this->items );
        $invoice->chargeTo( $this->account );
        return $invoice->process();
    }
}

これまで請求データが存在しないため、Bill クラスにはコンストラクターは必要ありません。

しかし、以前の請求書の管理にも同じ Bill クラスを使用したい場合は、データベースからすべての請求データをロードするコンストラクターが必要です。

class Bill {
    private $date;
    // --- other stuff

    function __construct( $bill_id ) {

        $result = mysql( "select * from invoices where id = $bill_id" );
        $this->date = $result['date'];
        // --- other stuff

    }

}

前者の場合はコンストラクターを実行すべきではなく、後者の場合は実行すべきであることをプログラムにどのように「伝える」ことができますか?

4

3 に答える 3

1

私は条件付き__constructキャンプにいます。

public class Bill {

    public function __construct( $bill_id = '' ){
        if (!empty($bill_id)) {
            $result = ...
        } 
    }
}

factory パターンも同様に機能します。必要なときにいつでも電話をかけることで怠惰になることはできませんnew Bill。状況に固有のメソッドを呼び出す必要があります。

于 2012-05-01T13:18:04.623 に答える
0

コンストラクターは変数を初期化するだけで、「実際の作業」を行うべきではありません。
クラスのインターフェースからのすべてのメソッドはテスト可能である必要があり、コンストラクターはインターフェースで宣言されるべきではないためです(そうしないと、このインターフェースは役に立たなくなります)。
詳細: http://misko.hevery.com/code-reviewers-guide/flaw-constructor-does-real-work/

于 2012-05-01T13:32:56.690 に答える
0

PHP は、コンストラクターのオーバーロードをサポートしていません。そのため、「工場パターン」を使用できます。

public class Bill(){

  private function __construct(){
    //prevent new Bill() called from outside the class
  }

  public static function createEmptyBill(){
    return new Bill();
  }

  public static function createBillFromData($bill_id){
    $bill = new Bill();
    //assign any var..
    return $bill;
  }
}
于 2012-05-01T12:46:20.120 に答える