Application and Bootstrap usage in ZendFramework tutorial

Source: Internet
Author: User
This article mainly introduces the Application and Bootstrap usage in the ZendFramework tutorial, and analyzes the functions of Application and Bootstrap in detail based on the instance form. the usage skills and related precautions are as follows, you can refer to the examples in this article to describe the Application and Bootstrap usage of the Zend Framework tutorial. We will share this with you for your reference. The details are as follows:

In an MVC application, we need to initialize and establish database links, configure views and view assistants, configure layout, register related plug-ins, and register action assistants, we need to complete these configurations and preparations one by one. Sometimes some initialization operations may be required, but in some cases these initialization operations may not be required. Zend_Application can not only perform these operations, but also make the configuration and initialization work more unified and orderly, with higher reusability.

Zend_Application can be subdivided into three types:

Zend_Application: load the PHP environment, including include_paths and automatic loading, and instantiate the pilot class.

Zend_Application_Bootstrap: provides the bootstrap class interface.

Zend_Application_Bootstrap_Bootstrap provides common functions for most bootstrap tasks, including dependency check and on-demand loading of bootstrap resources.

Zend_Application_Resource provides the function of loading resources on demand.

Developers can inherit Zend_Application_Bootstrap_Bootstrap as needed or implement the Zend_Application_Bootstrap_Bootstrapper interface. Load Zend_Application in the entry File (for example, public/index. php) and instantiate it based on the pilot options and the current environment configuration.

The guiding options include the specified guiding class file and guiding class path. the options are as follows:

Required include_paths

The automatic loading function loads the registered namespace.

Php. ini initialization settings

Specifies the bootstrap class name. if it is not "Bootstrap"

Resource prefix key-value pair key indicates the resource prefix name

Resource class name or alias

Path of the attached configuration file

Additional configuration options

The option can be an array, Zend_Config object, or a configuration file at the specified position.

Bootstrap Program

The second feature of Zend_Application is to guide the application. Bootstraps must implement the Zend_Application_Bootstrap_Bootstrapper interface. the specific API is as follows:

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();}

The api mainly provides environment configuration, obtains the resources for bootstrap loading, and the bootstrap program

You can implement the interface or inherit Zend_Application_Bootstrap_BootstrapAbstract, or Zend_Application_Bootstrap_Bootstrap.

Resource method

The resource methods that implement the Zend_Application_Bootstrap_BootstrapAbstract interface must follow the following rules. The Method type is protected and the method prefix must start with _ init will.

To load and use a resource method, add the resource name in bootstrap (). the resource name is the resource method with the _ init prefix removed.

If you want to load multiple resource methods, you can specify them through arrays.

For example, bootstrap class:

class Bootstrap extends Zend_Application_Bootstrap_Bootstrap{  protected function _initFoo()  {    // ...  }  protected function _initBar()  {    // ...  }  protected function _initBaz()  {    // ...  }}

Load only using _ initFoo ():

$bootstrap->bootstrap('foo');

Load and use _ initFoo () and _ initBar ():

$bootstrap->bootstrap(array('foo', 'bar'));

To load and use all resource methods, use bootstrap () without parameters ():

$bootstrap->bootstrap();

Create a first_web project

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

Later versions of zend framework introduce Zend_Application and Bootstrap. Zend_Application provides a reusable resource pilot, universal, and modular bootstrap class and dependency check. By default, PHP environment variables and automatic loading are set.

After a project is created by default, the following files are provided:

1. Bootstrap of the project

First_web/
── Application
│ ── Bootstrap. php

The code is as follows:

<?phpclass Bootstrap extends Zend_Application_Bootstrap_Bootstrap{}

2. configuration file

│ ── Configs
│ ── Application. ini

The code is as follows:

[production]phpSettings.display_startup_errors = 0phpSettings.display_errors = 0includePaths.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 = 1phpSettings.display_errors = 1[development : production]phpSettings.display_startup_errors = 1phpSettings.display_errors = 1resources.frontController.params.displayExceptions = 1

3. project portal file

── Public
│ ── Index. php

<?php// Define path to application directorydefined('APPLICATION_PATH')  || define('APPLICATION_PATH', realpath(dirname(__FILE__) . '/../application'));// Define application environmentdefined('APPLICATION_ENV')  || define('APPLICATION_ENV', (getenv('APPLICATION_ENV') ? getenv('APPLICATION_ENV') : 'production'));// Ensure library/ is on include_pathset_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();

The above code basically uses the Zend_Application method to initialize environment variables, load configuration files, initialize the environment, load modules, and complete the web application boot function.

Resource plugin

The resource plug-in only needs to implement Zend_Application_Resource_Resource, or, more simply, inherit Zend_Application_Resource_ResourceAbstract. The interface is as follows:

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();}

For example

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

Load resource plug-ins

I provide resource reusability, and can define the resource method as a resource plug-in ..

To enable bootstrap to identify resource plug-ins, Zend_Application_Bootstrap_ResourceBootstrapper must be implemented when defining resource plug-ins. the interface defines the search plug-ins, registers plug-ins, and loads plug-ins. APIs:

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();}

The use of resource plug-ins not only enables reuse of resources, but also makes bootstrap more concise. if you want to modify it, you do not need to modify your bootstrap to add resources.

You can use the defined resource plug-in only by implementing Zend_Application_Bootstrap_BootstrapAbstract (inherited by Zend_Application_Bootstrap_Bootstrap ).

You can register and use resource plug-ins by passing the specified options to application object and/or bootstrap. These options may be specified from a configuration file or manually. The rule is that the option must be a key-value pair, and the key represents the resource name. Resource name, which is the class prefix of the resource plug-in class. For example, the resource class prefix "Zend_Application_Resource _" that comes with the Zend Framework is the resource name. For example,

$application = new Zend_Application(APPLICATION_ENV, array(  'resources' => array(    'FrontController' => array(      'controllerDirectory' => APPLICATION_PATH . '/controllers',    ),  ),));

"FrontController" resources are special cases. The options are special.

Whether you use your own resource plug-ins or third-party resource plug-ins. You must ensure that bootstrap can find them. in bootstrap, Zend_Loader_PluginLoader allows you to specify the class prefix of the resource plug-in. you can easily register the resource plug-in by specifying the class path of the resource class.

For example, if the written resource plug-in is stored in APPLICATION_PATH/resources/, the class prefix is My_Resource. you can use the following method to register and load:

$application = new Zend_Application(APPLICATION_ENV, array(  'pluginPaths' => array(    'My_Resource' => APPLICATION_PATH . '/resources/',  ),  'resources' => array(    'FrontController' => array(      'controllerDirectory' => APPLICATION_PATH . '/controllers',    ),  ),));

Resources in the specified directory can be used in applications.

Similar to the resource method, you can use the bootstrap () method to load the resource plug-in. Load a single, multiple, all resource plug-ins are configured in a similar way.

For example:

// Execute one:$bootstrap->bootstrap('FrontController');// Execute several:$bootstrap->bootstrap(array('FrontController', 'Foo'));// Execute all resource methods and plugins:$bootstrap->bootstrap();

Resource Registry

To avoid repeated resource registration and unnecessary waste, Zend_Application_Bootstrap_BootstrapAbstract provides a local registry object to store these resource objects. when you want to store a resource, you only need to return the resource in the method.

For flexibility, the registry exists as an internal "container. All objects can be saved to the container. The resource name corresponds to the container property. By default, you can use Zend_Registry to obtain instances and customize other objects. The setContainer () and getContainer () methods can be used to manipulate the container itself. GetResource ($ resource) can be used to obtain a specified resource. HasResource ($ resource) can check whether the resource has been registered

For example, register a view resource:

class Bootstrap extends Zend_Application_Bootstrap_Bootstrap{  protected function _initView()  {    $view = new Zend_View();    // more initialization...    return $view;  }}

Resource-related operations:

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

Note: The Registry container is not global. This means that you need to obtain resources through the Accessed bootstrap. Zend_Application_Bootstrap_Bootstrap provides run (). after run () is executed, it registers as the "bootstrap" of the front-end controller parameter and obtains the vro, distributor, plug-in, and Action Controller through it.

Usage:

class FooController extends Zend_Controller_Action{  public function init()  {    $bootstrap = $this->getInvokeArg('bootstrap');    $view = $bootstrap->getResource('view');    // ...  }}

To prevent repeated registration of loading resource methods and plug-ins or some resources may depend on other resources. To solve these two problems, Zend_Application_Bootstrap_BootstrapAbstract provides a simple dependency tracking mechanism.

As mentioned above, all resources-whether method or plug-in-are loaded and run through bootstrap ($ resource), where $ resource is the resource name or resource name array, or empty. empty indicates loading and running all resources.

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.