Zend Framework 中的资源是什么时候初始化的呢?还是直接上代码来看比较有说服力
protected function _bootstrap($resource = null)
{
if (null === $resource) {
foreach ($this->getClassResourceNames() as $resource) {
$this->_executeResource($resource);
}
foreach ($this->getPluginResourceNames() as $resource) {
$this->_executeResource($resource);
}
} elseif (is_string($resource)) {
$this->_executeResource($resource);
} elseif (is_array($resource)) {
foreach ($resource as $r) {
$this->_executeResource($r);
}
} else {
throw new Zend_Application_Bootstrap_Exception('Invalid argument passed to ' . __METHOD__);
}
}
从上面的代码中可以看出,共有4种资源,其中前面加载了两种资源,一种是“类资源”,另一种是 Plugin资源,两种资源加载后,用
executeResource
进行调用。进行资源的初始化
下面再看看executeResource 函数
protected function _executeResource($resource)
{
$resourceName = strtolower($resource);
if (in_array($resourceName, $this->_run)) {
return;
}
if (isset($this->_started[$resourceName]) && $this->_started[$resourceName]) {
throw new Zend_Application_Bootstrap_Exception('Circular resource dependency detected');
}
$classResources = $this->getClassResources();
if (array_key_exists($resourceName, $classResources)) {
$this->_started[$resourceName] = true;
$method = $classResources[$resourceName];
$return = $this->$method();
unset($this->_started[$resourceName]);
$this->_markRun($resourceName);
if (null !== $return) {
$this->getContainer()->{$resourceName} = $return;
}
return;
}
if ($this->hasPluginResource($resource)) {
$this->_started[$resourceName] = true;
$plugin = $this->getPluginResource($resource);
$return = $plugin->init();
unset($this->_started[$resourceName]);
$this->_markRun($resourceName);
if (null !== $return) {
$this->getContainer()->{$resourceName} = $return;
}
return;
}
throw new Zend_Application_Bootstrap_Exception('Resource matching "' . $resource . '" not found');
}
从上面可以看出,对于“类资源” ,executeResource调用的是其类方法(以_init 打头的 ),而对于plugin资源,则调用其
init() 函数。
所以,如果要在run函数调用前初台化资源,只在在这两个地方放上代码即可.