为什么课程会多次重新申报?

时间:2010-02-22 21:11:10

标签: php zend-framework

好的,这是我用于在控制器操作中初始化模型的方法:

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

然后当我调用_getTable()方法两次时(例如在init()方法中调用一次,在控制器操作中调用一次),它会打印:

test test test test test test

在页面顶部。它不应该只是从_tables array()返回对象,因为array_key_exists()检查?换句话说,当多次调用该方法时,array_key_exists()函数内的部分不应只执行一次吗?

更新:

所以问题是这个 - 由于某种原因,布局被打印两次(因此它的布局被打印并且在布局内部有布局() - >内容;?>它再次打印布局)。我不知道它为什么这样做,因为它在以前的服务器和localhost上运行良好。

2 个答案:

答案 0 :(得分:3)

在您显示的代码段中:

protected $this->_tables = array();

这是无效的语法,应该是:

protected $_tables = array();

另外,为什么不使用include_once并让PHP为您处理这个问题?或者,您可以使用Zend_Loader。不要重新发明轮子。

答案 1 :(得分: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        

这种方法有点天真,但它应该给你很好的自动加载。