利用 Zend Framework 编程,个人一般偏爱以下方式作为程序入口,而不用完全自己组装
$application = new Zend_Application(APPLICATION_ENV, APPLICATION_PATH . '/configs/application.ini');
$application->bootstrap()->run();
所有的东西都放在配置文件里了,组装自动完成。
但现在的问题是,有一些操作需要在程序启动时就初始化,而不用经过路由,该如何实现呢?
方法是,在配置文件中指定的Bootstrap 类中实现。如下例:
//假设 配置文件中指定的Bootstrap 类为 Bootstrap
class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
{
protected function _initView ()
{
//TODO
}
protected function _initMenus ()
{
//TODO
}
protected function _initAutoload ()
{
//TODO
}
}
当类中的方法以 "_init" 打头时,bootstrap 类会在启动的时时候自动注册为类资源,见下面代码
abstract class Zend_Application_Bootstrap_BootstrapAbstract
implements Zend_Application_Bootstrap_Bootstrapper,
Zend_Application_Bootstrap_ResourceBootstrapper
{
//...
public function getClassResources()
{
if (null === $this->_classResources) {
if (version_compare(PHP_VERSION, '5.2.6') === -1) {
$class = new ReflectionObject($this);
$classMethods = $class->getMethods();
$methodNames = array();
foreach ($classMethods as $method) {
$methodNames[] = $method->getName();
}
} else {
$methodNames = get_class_methods($this);
}
$this->_classResources = array();
foreach ($methodNames as $method) {
if (5 < strlen($method) && '_init' === substr($method, 0, 5)) {
$this->_classResources[strtolower(substr($method, 5))] = $method;
}
}
}
return $this->_classResources;
}
//...
}
注册为类资源后,将会被自动调用,代码如下:
写道
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__);
}
}
{
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__);
}
}