Zend Framework Application与Bootstrap详解
本示例深入解析Zend Framework中Application与Bootstrap的核心用法,旨在为开发者提供实用的参考指南。
在构建MVC应用时,需完成数据库连接建立、视图及助手配置、布局设定、插件与Action助手注册等初始化工作。尽管部分场景下无需这些操作,但利用Zend_Application能将这些配置整合得更加规范有序,显著提升代码的重用性与管理效率。
Zend_Application的功能架构可划分为三个主要组成部分:
Zend_Application负责加载PHP运行环境,涵盖include_paths设置与自动加载机制,并负责实例化引导类。
Zend_Application_Bootstrap定义了引导类的标准接口。
Zend_Application_Bootstrap_Bootstrap实现了大多数通用引导功能,包括依赖检查以及资源的按需加载。
Zend_Application_Resource模块提供了资源的按需加载能力。
开发者可选择继承Zend_Application_Bootstrap_Bootstrap或实现Zend_Application_Bootstrap_Bootstrapper接口。在入口文件(如public/index.php)中加载Zend_Application后,依据引导选项及当前环境配置进行实例化。
引导选项包含指定的引导类文件路径及类路径,具体参数如下:
所需的include_paths列表
自动加载功能中额外注册的命名空间
php.ini中的初始化设置项
自定义bootstrap类名(若不为"Bootstrap")
资源前缀键值对,键代表资源前缀名称
资源的类名或别名标识
需附加加载的配置文件路径
额外的配置选项集合
上述选项可接受数组、Zend_Config对象或指定位置的配置文件作为值
引导程序主体
Zend_Application的另一核心功能是引导应用。Bootstraps必须实现Zend_Application_Bootstrap_Bootstrapper接口,其API定义如下:
interface Zend_Application_Bootstrap_Bootstrapper
{
public function __construct($application);
public function setOptions(array $options);
public function getApplication();
public function getEnvironment();
public function getClassResources();
public function getClassResourceNames();
public function bootstrap($resource = null);
public function run();
}
该接口主要提供环境配置访问、获取已加载资源以及执行引导程序的方法。
实现方式既可直接实现接口,也可继承Zend_Application_Bootstrap_BootstrapAbstract或Zend_Application_Bootstrap_Bootstrap类。
资源方法规范
实现Zend_Application_Bootstrap_BootstrapAbstract接口的资源方法需遵循特定规则:方法可见性必须为protected,且方法名必须以_init开头。
若需加载并使用某个资源方法,只需在bootstrap()调用中传入该资源名称,即去掉_init前缀后的部分。
若需加载多个资源方法,可通过传递数组形式指定。
例如,定义一个Bootstrap类:
class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
{
protected function _initFoo()
{
// ...
}
protected function _initBar()
{
// ...
}
protected function _initBaz()
{
// ...
}
}
仅加载使用_initFoo()方法:
$bootstrap->bootstrap('foo');
同时加载使用_initFoo()和_initBar()方法:
$bootstrap->bootstrap(array('foo', 'bar'));
加载所有可用的资源方法,直接调用无参的bootstrap()即可:
$bootstrap->bootstrap();
新建first_web项目
root@coder-671T-M:/mydev_src/zend_framework_learn/www# tree first_web/ first_web/ ├── application │ ├── Bootstrap.php │ ├── configs │ │ └── application.ini │ ├── controllers │ │ ├── ErrorController.php │ │ └── IndexController.php │ ├── models │ └── views │ ├── helpers │ └── scripts │ ├── error │ │ └── error.phtml │ └── index │ └── index.phtml ├── docs │ └── README.txt ├── library ├── public │ └── index.php └── tests ├── application │ └── controllers │ └── IndexControllerTest.php ├── bootstrap.php ├── library └── phpunit.xml 16 directories, 11 files
较新版本的Zend Framework引入了Zend_Application和Bootstrap机制。Zend_Application提供了可重用资源的引导支持,具备通用、模块化及依赖检查功能的引导类,并默认负责设置PHP环境变量与自动加载功能。
默认新建项目后,会生成以下关键文件结构:
1. 项目的Bootstrap引导类
first_web/ ├── application │ ├── Bootstrap.php
具体代码如下:
<?php
class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
{
}
2. 配置文件
│ ├── configs │ │ └── application.ini
具体代码如下:
[production]
phpSettings.display_startup_errors = 0
phpSettings.display_errors = 0
includePaths.library = APPLICATION_PATH "/../library"
bootstrap.path = APPLICATION_PATH "/Bootstrap.php"
bootstrap.class = "Bootstrap"
appnamespace = "Application"
resources.frontController.controllerDirectory = APPLICATION_PATH "/controllers"
resources.frontController.params.displayExceptions = 0
[staging : production]
[testing : production]
phpSettings.display_startup_errors = 1
phpSettings.display_errors = 1
[development : production]
phpSettings.display_startup_errors = 1
phpSettings.display_errors = 1
resources.frontController.params.displayExceptions = 1
3. 项目入口文件
├── public │ └── index.php
<?php
// Define path to application directory
defined('APPLICATION_PATH')
|| define('APPLICATION_PATH', realpath(dirname(__FILE__) . '/../application'));
// Define application environment
defined('APPLICATION_ENV')
|| define('APPLICATION_ENV', (getenv('APPLICATION_ENV') ? getenv('APPLICATION_ENV') : 'production'));
// Ensure library/ is on include_path
set_include_path(implode(PATH_SEPARATOR, array(
realpath(APPLICATION_PATH . '/../library'),
get_include_path(),
)));
/** Zend_Application */
require_once 'Zend/Application.php';
// Create application, bootstrap, and run
$application = new Zend_Application(
APPLICATION_ENV,
APPLICATION_PATH . '/configs/application.ini'
);
$application->bootstrap()
->run();
上述代码展示了基本使用Zend_Application的方式,完成了环境变量初始化、配置文件加载、环境初始化、模块加载及Web应用程序的完整引导功能。
资源插件机制
资源插件只需实现Zend_Application_Resource_Resource接口,或更简便地继承Zend_Application_Resource_ResourceAbstract。接口定义如下:
interface Zend_Application_Resource_Resource
{
public function __construct($options = null);
public function setBootstrap(
Zend_Application_Bootstrap_Bootstrapper $bootstrap
);
public function getBootstrap();
public function setOptions(array $options);
public function getOptions();
public function init();
}
例如
class My_Resource_View extends Zend_Application_Resource_ResourceAbstract
{
protected $_view;
public function init()
{
// Return view so bootstrap will store it in the registry
return $this->getView();
}
public function getView()
{
if (null === $this->_view) {
$options = $this->getOptions();
$title = '';
if (array_key_exists('title', $options)) {
$title = $options['title'];
unset($options['title']);
}
$view = new Zend_View($options);
$view->doctype('XHTML1_STRICT');
$view->headTitle($title);
$view->headLink()->appendStylesheet('/css/site.css');
$view->headScript()->appendfile('/js/analytics.js');
$viewRenderer =
Zend_Controller_Action_HelperBroker::getStaticHelper(
'ViewRenderer'
);
$viewRenderer->setView($view);
$this->_view = $view;
}
return $this->_view;
}
}
加载使用资源插件
为提高资源重用性,可将资源方法定义为资源插件。
为了让bootstrap识别资源插件,定义时需实现Zend_Application_Bootstrap_ResourceBootstrapper接口。该接口定义了查找、注册和加载插件的API:
interface Zend_Application_Bootstrap_ResourceBootstrapper
{
public function registerPluginResource($resource, $options = null);
public function unregisterPluginResource($resource);
public function hasPluginResource($resource);
public function getPluginResource($resource);
public function getPluginResources();
public function getPluginResourceNames();
public function setPluginLoader(Zend_Loader_PluginLoader_Interface $loader);
public function getPluginLoader();
}
采用资源插件不仅提升资源重用率,还使bootstrap代码更简洁。新增或修改资源时无需改动bootstrap主体逻辑。
只有通过实现Zend_Application_Bootstrap_BootstrapAbstract(被Zend_Application_Bootstrap_Bootstrap继承),才能使用定义的资源插件。
通过将指定选项传递给application对象和/或bootstrap来注册资源插件。选项可来自配置文件或手动指定。规则是选项必须为键值对,键代表资源名称,即资源插件类的类前缀。例如,Zend框架自带资源类前缀为“Zend_Application_Resource_”,其后部分即为资源名称。例如,
$application = new Zend_Application(APPLICATION_ENV, array(
'resources' => array(
'FrontController' => array(
'controllerDirectory' => APPLICATION_PATH . '/controllers',
),
),
));
"FrontController"资源是一个特例,其选项较为特殊。
无论是自写还是第三方资源插件,必须确保bootstrap能找到它们。bootstrap内部通过Zend_Loader_PluginLoader,只需指定资源插件的类前缀及类路径即可轻松注册。
例如,若编写的资源插件存放在APPLICATION_PATH/resources/目录下,类前缀为My_Resource,可使用如下方法注册加载:
$application = new Zend_Application(APPLICATION_ENV, array(
'pluginPaths' => array(
'My_Resource' => APPLICATION_PATH . '/resources/',
),
'resources' => array(
'FrontController' => array(
'controllerDirectory' => APPLICATION_PATH . '/controllers',
),
),
));
在应用程序中还可以使用指定目录下的资源。
与资源方法类似,通过bootstrap()方法可加载资源插件。加载单一、多个或全部资源插件的配置方式也类似。
例如:
// Execute one:
$bootstrap->bootstrap('FrontController');
// Execute several:
$bootstrap->bootstrap(array('FrontController', 'Foo'));
// Execute all resource methods and plugins:
$bootstrap->bootstrap();
资源注册表
为避免资源重复注册造成的浪费,Zend_Application_Bootstrap_BootstrapAbstract提供了一个本地注册表对象来存储资源对象。在方法中返回资源即可将其存入。
为保持灵活性,注册表作为内部“容器”存在,任何对象均可存入,资源名称对应容器属性。默认情况下,可通过Zend_Registry获取实例,也可自定义其他对象。setContainer()和getContainer()方法用于操纵容器本身,getResource($resource)用于获取指定资源,hasResource($resource)用于检查资源是否已注册。
例如,注册一个view资源:
class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
{
protected function _initView()
{
$view = new Zend_View();
// more initialization...
return $view;
}
}
资源的相关操作:
// Using the has/getResource() pair:
if ($bootstrap->hasResource('view')) {
$view = $bootstrap->getResource('view');
}
// Via the container:
$container = $bootstrap->getContainer();
if (isset($container->view)) {
$view = $container->view;
}
注意:注册表容器并非全局共享。这意味着需要通过访问bootstrap来获取资源。Zend_Application_Bootstrap_Bootstrap提供了run()方法,执行run()后,它会将自身注册为前端控制器参数的“bootstrap”,借此可获取路由器、分发器、插件和动作控制器。
具体使用方法:
class FooController extends Zend_Controller_Action
{
public function init()
{
$bootstrap = $this->getInvokeArg('bootstrap');
$view = $bootstrap->getResource('view');
// ...
}
}
为防止资源方法和插件的重复注册加载,以及解决资源间的依赖问题,Zend_Application_Bootstrap_BootstrapAbstract提供了一种简单的依赖跟踪机制。
如前所述,所有资源——无论是方法还是插件——均通过bootstrap($resource)加载运行,其中$resource为资源名称、资源名称数组或为空(为空表示加载运行所有资源)。
class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
{
protected function _initRequest()
{
// Ensure the front controller is initialized
$this->bootstrap('FrontController');
// Retrieve the front controller from the bootstrap registry
$front = $this->getResource('FrontController');
$request = new Zend_Controller_Request_Http();
$request->setBaseUrl('/foo');
$front->setRequest($request);
// Ensure the request is stored in the bootstrap registry
return $request;
}
}
希望本文所述对大家PHP程序设计有所帮助。