结构
- Db类用于数据库连接。 - Settings类,从数据库中检索设置。 - Languages类,检索特定语言的信息。 - Page类,Product类,Customer类等等。
思路 Settings类需要Db类来检索设置。 Languages类需要Db和Settings来根据从数据库获取的设置检索信息。 Page类需要Db、Settings和Languages。它未来可能还需要一些其他类。
简化代码
Db.php继承PDO
Settings.php
class Settings
{
/* Database instance */
protected $db;
/* Cached settings */
private $settings = array();
public function __construct(Db $db)
{
$this->db = $db;
}
public function load ()
{
$selq = $this->db->query('SELECT setting, value FROM settings');
$this->settings = $selq->fetchAll();
}
}
Languages.php
class Languages
{
public $language;
protected $db;
protected $settings;
private $languages = array();
public function __construct(Db $db, Settings $settings)
{
$this->db = $db;
$this->settings = $settings;
// set value for $this->language based on user choice or default settings
...
}
public function load()
{
$this->languages = array();
$selq = $this->db->query('SELECT * FROM languages');
$this->languages = $selq->fetchAll();
}
}
Page.php
class Page
{
protected $db;
protected $settings;
protected $language;
public function __construct(Db $db, Settings $settings, Languages $languages)
{
$this->db = $db;
$this->settings = $settings;
$this->languages = $languages;
}
public function load()
{
// load page info from db with certain settings and in proper language
...
}
}
Config.php
$db = new Db;
/* Load all settings */
$settings = new Settings($db);
$settings->load();
/* Load all languages */
$languages = new Languages($db, $settings);
$languages->load();
/* Instantiate page */
$page = new Page($db, $settings, $languages);
我不喜欢重复地注入相同的类。这样,当我需要注入10个类时,我就会遇到问题。所以,我的代码从一开始就是错误的。
也许更好的方法是这样做:
Config.php
$db = new Db;
/* Load all settings */
$settings = new Settings($db);
$settings->load();
/* Load all languages */
$languages = new Languages($settings);
$languages->load();
/* Instantiate page */
$page = new Page($languages);
由于设置(Settings)已经可以访问$db,语言(Languages)也可以同时访问$db和$settings。
然而,以这种方式,我需要进行如下调用:$this->languages->settings->db-...
我的所有代码架构似乎完全错误了 :)
应该如何做呢?