douchen4915 2013-04-30 09:55
浏览 43

将Zend模型定义为Singleton

I want to put my Zend Model as Singleton, so I have done this:

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
}}

I instantiate my model like so:

        $dossiercasModel =  Social_Model_DbTable_Dossier::GetInstance();

but this erreur is occured:

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

when I put the constructor of the Model as public it works fine but this is inconsistent with the notion of singleton!

  • 写回答

1条回答 默认 最新

  • doue2666 2013-05-10 21:30
    关注

    In the past I have gotten arround having to do this by creating a table broker that would serve up cached table instances, kind of a multiton.

    a simple example

    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);
       }
    }
    

    To use to get an instance of My_User_Table you would could:

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

    or

    $table = My_TableManager::getInstnace()->getTable("My_Table");
    
    评论

报告相同问题?

悬赏问题

  • ¥15 IAR程序莫名变量多重定义
  • ¥15 (标签-UDP|关键词-client)
  • ¥15 关于库卡officelite无法与虚拟机通讯的问题
  • ¥100 已有python代码,要求做成可执行程序,程序设计内容不多
  • ¥15 目标检测项目无法读取视频
  • ¥15 GEO datasets中基因芯片数据仅仅提供了normalized signal如何进行差异分析
  • ¥100 求采集电商背景音乐的方法
  • ¥15 数学建模竞赛求指导帮助
  • ¥15 STM32控制MAX7219问题求解答
  • ¥20 在本地部署CHATRWKV时遇到了AttributeError: 'str' object has no attribute 'requires_grad'