这是我的核心构造:
public $objDb;
public $objConfig;
public $configData;
public $objUrl;
public $objController;
public function __construct() {
$this->objDb = new Dbase();
$this->objConfig = new Config($this->objDb);
$this->objUrl = new Url($this->objDb);
$this->objController = new Controller($this->objUrl, $this->objConfig);
}
正如您所看到的,我将%objDb传递给每个新类,因此我不必在每个新类中创建新的类DB,这意味着保存与数据库的连接(我认为)
但这是好的做法吗? 我应该在url类中创建$ objDb = new Dbase(); 现在在URL中
public function __construct($db) {
$this->objDb = $db;
$this->process();
}
更新
感谢您的回复 - 特别是关于依赖注入。
还有一个问题是否可以这样做 在课堂核心:
public function __construct() {
$this->objDb = new Dbase();
$this->objUrl = new Url();//EMPTY
$this->objController = new Controller($this->objUrl, $this->objConfig);
}
IN CLASS URL
public function __construct() {
$this->objDb = Dbase $db;//declared already in core
$this->process();
}