【发布时间】:2015-03-29 21:11:07
【问题描述】:
在两个继承的类之间共享类实例的最佳方式是什么?
// Let's create a main class that hold common methods and connects to the database
class MyApp {
public $DB;
function __construct () {
// Connect to the database here
$this->DB = new Database();
}
}
// This will hold methods specific to the user management
class Users extends MyApp {
function __construct() {
parent::__construct();
}
}
// This will hold methods specific for fetching news articles
class News extends MyApp {
function __construct() {
parent::__construct();
}
}
现在,在我的应用程序中,我的页面在同一页面上同时显示用户和新闻。所以我做了这样的事情:
// Instantiate the users class (this will connect to the db)
$users = new Users();
// Instantiate the news calls (PROBLEM! This will create a new db connection instead of re-using the previous one)
$news = new News();
我可以将数据库实例分开,然后将其传入。像这样:
$db = new Database();
$users = new Users($db);
$news = new News($db);
但是现在我到处传递这个愚蠢的 $db 变量——感觉很混乱而且容易出错。
有没有更好的方法来构建它?理想的解决方案如下所示:
// Instantiate a global class which will connect the DB once
$App = new MyApp();
// Reference sub-classes which all share the parent class variables.
// Unfortunately PHP doesn't seem to have sub-class support :(
$App->Users->someMethod();
$App->News->someMethod();
【问题讨论】:
-
“我可以将数据库实例分开,然后将其传入”。这是正确的做法,尤其是从 TDD 的角度来看。
标签: php