2010-02-22 14 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

相关问题