2012-06-14 35 views
1

我目前這樣做,在一個類變量中存儲一個類是我做對了嗎? PHP

class Page { 
    // variable to hold DBC class 
    public $dbc; 
    /* 
     __CONSTRUCT 
     Called when class is initiated and sets the dbc variable to hold the DBC class. 
    */ 
    public function __construct() { 
     // set the dbc variable to hold the DBC class 
     $this -> dbc = new DBC(); 
    } 
    /* 
     CREATE PAGE 
     Create a page with the option to pass data into it. 
    */ 
    public function create($title, $class, $data = false) { 
     // start buffer 
     ob_start('gz_handler'); 
     // content 
     content($this -> dbc, $data); 
     // end buffer and flush 
     ob_end_flush(); 
    } 

}

我簡單的例子,但基本上我需要的對象DBC傳遞給函數的方法create裏面?

這被認爲是不好的做法,因爲我是用以前,但extends意識到沒有辦法擴展的類提取到一個變量?

感謝

回答

4

你非常接近dependency injection設計模式。

你只需要改變你的構造函數接受對象作爲參數,像這樣:

public function __construct($dbc) { 
    // set the dbc variable to hold the DBC class 
    $this -> dbc = $dbc; 
} 

然後與數據庫的連接實例類,像這樣:

$dbc = new DBC(); 
$page = new Page($dbc); 

這有各種各樣的好處,從簡單到測試,到連接數據庫的單一連接。想象一下,你需要五個Page對象 - 現在你傳遞它們所有相同的數據庫連接,所以它們不需要單獨創建一個。

+0

好吧我現在明白了:)如果沒有問題,還有一個問題,但爲什麼這種方式比我給的方式更優先?在課堂內發起課程或類似的東西不好?謝謝 – Griff

+0

您已經編輯!再次感謝好友:) – Griff

+0

不是問題:) – nickb

相關問題