0

我想把我的 Zend 模型作为单例,所以我这样做了:

class Social_Model_DbTable_Dossier extends Zend_Db_Table_Abstract {

private static $_instance;

public static function GetInstance() {
    if (!self::$_instance instanceof self) {
        self::$_instance = new self();
    }
    return self::$_instance;
}

private function __construct() {
    // put normal constructor code.
    // it will only ever be called once
}}

我像这样实例化我的模型:

        $dossiercasModel =  Social_Model_DbTable_Dossier::GetInstance();

但是发生了这个错误:

Fatal error: Access level to Social_Model_DbTable_Dossier::__construct() must be public (as in class Zend_Db_Table_Abstract)

当我将模型的构造函数设为公共时,它可以正常工作,但这与单例的概念不一致!

4

1 回答 1

0

在过去,我不得不通过创建一个表代理来提供缓存的表实例,这种代理是多吨的。

一个简单的例子

class My_TableManager{

   protected static $_instance;
   protected $_tableCache = array();

   protected function __construct(){

   }

   public static function getInstance(){
       if (!isset(self::$_instance)) self::$_instance = new self();
   }

   public function getTable($tableName){
        if (!array_key_exists($tableName, $this->_tableCache)){
            // you can do fun stuff here like name inflection
            // Im assuming that tables will be suffixed with _Table
            $tableClass = "My_".$tableName."_Table";
            $this->_tableCache[$tableName] = new $tableClass();
        }
        return $this->_tableCache[$tableName];
   }

   public static function get($tableName){
        return self::getInstance()->getTable($tableName);
   }
}

要使用获取 My_User_Table 的实例,您可以:

$table = My_TableManager::get("My_User");

或者

$table = My_TableManager::getInstnace()->getTable("My_Table");
于 2013-05-10T21:30:43.470 回答