将Zend模型定义为Singleton

时间:2013-04-30 09:55:16

标签: php zend-framework constructor singleton

我想把我的Zend模型作为Singleton,所以我做了这个:

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)

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

1 个答案:

答案 0 :(得分: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");