简体   繁体   English

Zend Framework-构造函数中的Db适配器为null

[英]Zend Framework - Db Adapter in constructor is null

ZF Version: 1.11.2 ZF版本:1.11.2

I want to create an abstract class, which holds my db adapter. 我想创建一个抽象类,其中包含我的数据库适配器。 Simplified it looks like this: 简化后看起来像这样:

<?php
class Application_Model_DbTable_Abstract extends Zend_Db_Table_Abstract
{
    protected $_dbAdapter = null;

    /**
     * @return null
     */
    public function getDbAdapter()
    {
        return $this->_dbAdapter;
    }

    /**
     * @param null $dbAdapter
     */
    public function setDbAdapter($dbAdapter)
    {
        $this->_dbAdapter = $dbAdapter;
    }

    public function __construct()
    {
        \Zend_Debug::dump($this->getAdapter(), 'Datei: ' . __FILE__ . '<br/>Zeile: ' . __LINE__, true); die;
    }
}

But my dump returns null. 但是我的转储返回null。 In a basic model class (which extends from Zend_D b_Table_Abstract) the same dump returns an Zend_Db_Adapter_Pdo_Mysql object. 在基本模型类(从Zend_D b_Table_Abstract扩展)中,同一转储将返回Zend_Db_Adapter_Pdo_Mysql对象。 Why? 为什么?

I had a little look at the Zend DB source code just to refresh my memory. 我稍微看了一下Zend DB源代码,只是为了刷新内存。 If you change your constructor to this: 如果将构造函数更改为此:

public function __construct($config = array())
{
    parent::__construct($config);

    \Zend_Debug::dump($this->getAdapter(), 'Datei: ' . __FILE__ . '<br/>Zeile: ' . __LINE__, true); die;
}

It should work more like you're expecting. 它应该更像您期望的那样工作。

Answering the question from your comment: the getAdapter() method of Zend_Db_Table_Abstract simply returns whatever's in the DB adapter variable. 从您的评论中回答问题: Zend_Db_Table_AbstractgetAdapter()方法仅返回数据库适配器变量中的内容。 It doesn't do anything with the default. 它对默认值不做任何事情。 Also, since your class overrides that method, your version will be used instead. 另外,由于您的类会覆盖该方法,因此将使用您的版本。

The constructor in the Zend_Db_Table_Abstract class will set a default if one wasn't provided, so calling the parent constructor as in my example should ensure a default adapter is set. 如果未提供,则Zend_Db_Table_Abstract类中的构造函数将设置默认值,因此像我的示例中那样调用父构造函数应确保设置了默认适配器。

Also, ZF1 is past end of life. 此外,ZF1即将过期。 You shouldn't use it for new applications, and should be planning migration for current ones. 您不应该将其用于新应用程序,而应该为当前应用程序计划迁移。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM