我想把我的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)
当我把模型的构造函数作为公共时,它工作得很好,但这与单例的概念不一致!
过去,我通过创建一个表代理来提供缓存的表实例,从而绕过了必须这样做的问题。有点多。
一个简单的例子
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");