2010-02-22 50 views
0

確定這裏是我用我的控制器操作初始化模型的方法:爲什麼類會多次重新聲明?

protected $_tables = array(); 

protected function _getTable($table) 
{ 
    if (false === array_key_exists($table, $this->_tables)) { 
     include APPLICATION_PATH . '/modules/' 
     . $this->_request->getModuleName() . '/models/' . $table . '.php'; 
     $this->_tables[$table] = new $table(); 
     echo 'test '; 
    } 
    return $this->_tables[$table]; 
} 

然後當我在控制器動作曾經在init()方法調用_getTable()方法兩次(例如,一旦)它打印:

test test test test test test 

在頁面頂部。不應該因爲array_key_exists()檢查而從_tables array()返回對象嗎?換句話說,當方法被多次調用時,array_key_exists()函數中的部分不應該只執行一次嗎?

UPDATE:

所以,問題是這樣的 - 由於某種原因,佈局被打印兩次(所以它的佈局打印,那裏是佈局()裏面的佈置 - >含量>再次打印佈局? )。我不知道爲什麼它這樣做,因爲它在以前的服務器上以及在本地主機上運行良好。

+0

你確定你的變量/屬性包含你所期望的嗎?如果你在'_getTable'方法的開頭添加了'var_dump($ table,$ this - > _ tables)'',你會得到什麼? – 2010-02-22 21:16:54

+0

您也可以將'echo'test';'替換爲'echo'測試{$ table}。「;' - 也許您會在別的地方將它稱爲您忘記的地方。 – thetaiko 2010-02-22 21:21:49

+0

當我var_dump _tables數組看起來應該是,沒有重複的條目。 – 2010-02-22 21:32:41

回答

3

在摘要中顯示您:

protected $this->_tables = array(); 

這不是有效的語法,它應該是:

protected $_tables = array(); 

而且,爲什麼不使用include_once讓PHP處理這個的嗎?或者,您可以使用Zend_Loader。不要重新發明輪子。

1

您真正需要的是基於模塊的資源加載。爲什麼不使用ZF的(模塊)資源自動加載器來重新發明輪子呢?請參閱文檔:

http://framework.zend.com/manual/en/zend.loader.autoloader-resource.html

當您使用Zend_Application(我假設你沒有),你會自動獲得這些。如果你不能這樣做

$loaders = array(); 
$frontController = Zend_Controller_Front::getInstance(); 

foreach($frontController->getControllerDirectory() as $module => $directory) { 

    $resourceLoader = new Zend_Application_Module_Autoloader(array(
     'namespace' => ucfirst($module) . '_', 
     'basePath' => dirname($directory), 
    )); 

    $resourceLoader->addResourceTypes(array(
     'table' => array(
      'path'  => 'models/', 
      'namespace' => 'Table' 
    )); 

    $loaders[$module] = $resourceLoader; 
} 
//build array of loaders 

$loader = Zend_Loader_Autoloader::getInstance(); 
$loader->setAutoloaders($loaders); 
//set them in the autoloader   

這種方法有點天真,但它應該給你很好的自動加載。

+0

我實際上使用Zend_Application,而不是Zend_Loader,我使用本地php __autoload()函數,像這個函數__autoload($ class){ include str_replace('_','/',$ class)。 '.PHP'; }。無論如何,我已經認識到這個問題,有一個控制器插件干擾並引起所有的麻煩,現在它工作:) – 2010-02-24 12:52:22