【问题标题】:Instantiate the db connection in a parent class then its children classes can inherit from it?在父类中实例化数据库连接,然后它的子类可以继承它吗?
【发布时间】:2014-09-22 03:59:51
【问题描述】:

类中实例化数据库连接然后其子类可以继承是个好主意吗?

例如,这是我的核心模型,

class CoreModel
{
    protected $connection;

    public function __construct() 
    {
        // Construct database connection data.
        $this->connection = new Database(DSN,DB_USER,DB_PASS);
        $this->connection->connect();
    }

}

然后我有这些从CoreModel 扩展的类,

class Article extends CoreModel
{
    public function __construct()
    {
        parent::__construct();
    }
}

class Image extends CoreModel
{
    public function __construct()
    {
        parent::__construct();
    }
}

class Controller extends CoreModel
{
    public function __construct()
    {
        parent::__construct();
    }
}

它会导致数据库连接无限次吗?那么在我上面的例子中,这将是 3 db 连接?

如果这是一个坏主意,那么实例化数据库连接一次以便所有类都可以依赖它的基本方法是什么?

编辑:

$connection = new Database(DSN,DB_USER,DB_PASS);
$connection->connect();

$controller = new Controller($connection);
$article = new Article($connection);

class Article {

    protected $connection;

    public function __construct(Database $connection) {
        $this->connection = $connection;
    }

}

【问题讨论】:

标签: php inheritance pdo multiple-inheritance


【解决方案1】:

是的,这是个坏主意。构造函数代码将为每个孩子单独执行,最终您将拥有多个数据库连接。除此之外,用特定的数据库连接硬编码某个类是个坏主意。你应该将dependency injecting数据库连接成构造函数:

class Article {

    protected $connection;

    public function __construct(Database $connection) {
        $this->connection = $connection;
    }

}

虽然拥有一个可以直接访问数据库的“模型类”似乎也是个坏主意。你应该仔细阅读这个问题:Looking for a way to handle/approach PHP OOP websites

【讨论】:

  • 感谢您的回答。你的意思是我应该像我上面的编辑那样在方法中做吗?
  • public function __construct(Database $connection){...} 中添加前缀Database 也是为了什么
  • 还有hardcode a certain class with a specific database connection. in Beyond that, it's a bad idea to hardcode a certain class with a specific database connection.是什么意思?
  • 不,您在Article 之外实例化$connection,然后在构造它时将其传递给Articlenew Article($connection)。而函数签名中的Database是一个类型提示,需要一个Database对象。
  • 我的意思是你通过在其构造函数中实例化数据库连接使你的代码不灵活。请阅读How Not To Kill Your Testability Using Statics,然后阅读问题中链接的其他问答,然后阅读依赖注入。真的不难,但所有的思考和推理都不能在一条评论中解释。
猜你喜欢
  • 1970-01-01
  • 2018-05-06
  • 1970-01-01
  • 2023-03-27
  • 1970-01-01
  • 1970-01-01
  • 2017-02-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多