【发布时间】:2017-05-08 04:40:59
【问题描述】:
我有一个包含全局使用方法的类,并通过扩展类来使用它们:
App.php
final class App extends Core {
// The app class handles routing and basically runs the show
}
Core.php
abstract class Core {
public function __construct() { // Here we bring in other classes we use throughout the app
$this->Db = new Db($this);
$this->Mail = new Mail($this);
}
// Then we define multiple methods used throughout the app
public function settings($type) {
// You see this used by the model below
}
}
index.php
$App = new App(); // This fires up the app and allows us to use everything in Core.php
到目前为止,这一切都很好,因为整个站点的所有内容都在 $App 内处理。但是,在我的 MVC 结构中,模型需要从数据库中提取数据,以及检索所有包含在 Core 中的其他设置。我们不需要模型使用整个$App 类,但我们需要Core。
MyModel.php
class MyModel extends Core {
public function welcome() {
return 'Welcome to '.$this->settings('site_name');
}
}
一旦MyModel.php 起作用,Core 构造函数就会第二次运行。如何防止Core 构造函数运行两次?
【问题讨论】:
-
这篇文章可能会有所帮助:stackoverflow.com/questions/23160509/…
-
你的 App 类不应该访问 db.. 只有模型应该这样做..
-
作为一个不能有多个实例的App类,你可以使用Singleton模式(这只是一个提示,小心Singleton模式,“强大的力量来自巨大的责任”)。 App 类不应访问存储。可以使用很多模式,Register 模式、Service Provider(即 Register)或 Connection Manager 可以管理您的服务实例。依赖注入(如前所述)是共享依赖的最佳方式,无需在没有控制的情况下创建。
标签: php