Application and bootstrap usages of Zend framework Tutorials _php Examples

Source: Internet
Author: User
Tags zend zend framework

This example describes the application and bootstrap usage of the Zend Framework tutorial. Share to everyone for your reference, specific as follows:

In an MVC application, we need to initialize the database link, configure the View and view assistant, configure the layout, register the relevant plug-ins, register the Action Assistant, and so on, and we all need one by one to complete the configuration and preparation. Sometimes there may be some initialization required, but in some cases these initializations may not be required. The zend_application not only accomplishes these things, but also makes these configurations and initialization work more uniform and more reusable.

Zend_application can be subdivided into three types:

Zend_application: Load the PHP environment, including include_paths and auto load, and instantiate the boot class.

Zend_application_bootstrap: Provides an interface to the boot class.

Zend_application_bootstrap_bootstrap completes the common functionality that most boot needs provide, including dependency checking and on-demand loading of boot resources.

Zend_application_resource provides resources on-demand loading features

Developers can inherit zend_application_bootstrap_bootstrap or implement Zend_application_bootstrap_bootstrapper interfaces as needed. Loads zend_application in a portal file (for example, public/index.php) and is instantiated based on the boot option and the current environment configuration.

The boot options include the specified boot class file and boot Classpath, with the following options:

The include_paths you need.

Auto Load feature extra loading of registered namespaces

PHP.ini Initialization settings

Specifies the Bootstrap class name, if it is not "Bootstrap"

The prefix key-value pairs for the resource represent the resource prefix name

The class name or alias of the resource

Additional loaded configuration file path

Additional configuration options

The option can be an array, or a Zend_config object, or a configuration file at the specified location

Boot program

Zend_application's second function is to boot the application, bootstraps must implement the Zend_application_bootstrap_bootstrapper interface, the specific interface 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 ();
}

APIs mainly provide environment configuration, get bootstrap loaded resources, and boot program

You can implement interfaces or inherit Zend_application_bootstrap_bootstrapabstract, or Zend_application_bootstrap_bootstrap.

Resource methods

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 be _init will to begin with.

If you want to load a resource method, add a resource name in Bootstrap (), and the resource name is the resource method that removes the _init prefix.

If you are loading using multiple resource methods, you can specify them by array.

For example Bootstrap class:

Class Bootstrap extends Zend_application_bootstrap_bootstrap
{
  protected function _initfoo ()
  {
    // ...
  }
  protected function _initbar ()
  {
    //...
  }
  protected function _initbaz ()
  {
    //...
  }
}

Only load using _initfoo ():

$bootstrap->bootstrap (' foo ');

Load using _initfoo () and _initbar ():

$bootstrap->bootstrap (Array (' foo ', ' Bar '));

Load using all resource methods, using Bootstrap ():

$bootstrap->bootstrap ();

New 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
directories, files

The newer version of the Zend Framework introduces zend_application and Bootstrap. Zend_application provides a guide to reusable resources, generic and modular boot classes, and dependency checking. At the same time, the default is responsible for setting PHP environment variables and automatic loading functions.

When you create a new project by default, several files are given:

1. Bootstrap of the project

first_web/
├──application
│├──bootstrap.php

The specific code is as follows:

<?php
class Bootstrap extends Zend_application_bootstrap_bootstrap
{
}

2. Configuration file

│├──configs
││└──application.ini

The specific code is as follows:

[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. Project entry Document

├──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 ();

The above code is the basic use of Zend_application way, completed the initialization of environment variables, loading configuration files, initializing the environment, loading modules, complete the Web application boot function.

Resource Plug-ins

Resource Plug-ins only need 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 would store it in the registry return $this->getview ();
      The 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 Use resource Plug-in

I am. Provide reuse of resources, you can define resource methods as resource Plug-ins ...

In order for Bootstrap to identify resource plug-ins, it is necessary to implement zend_application_bootstrap_resourcebootstrapper when defining resource plug-ins. The interface defines the lookup plug-in, registers the plug-in, and loads the plug-in's 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 ();
}

The use of resource plug-ins, not only allows resources to re-use, while allowing bootstrap more concise, if you want to modify, add resources do not need to modify your bootstrap.

You can use a defined resource plug-in by implementing Zend_application_bootstrap_bootstrapabstract (inherited by Zend_application_bootstrap_bootstrap)

Registers the use of a resource plug-in by passing the specified options to the Application object and/or bootstrap. These options may be specified from a configuration file, or by hand. The rule is that the option must be a key-value pair, and the key represents the resource name. The resource name, which is the class prefix for the resource plug-in class. For example, the Zend framework has its own resource class prefix "Zend_application_resource_", and any of the following, this is the name of the resource. For example

$application = new Zend_application (application_env, Array (
  ' resources ' => array (
    ' Frontcontroller ' => Array (
      ' controllerdirectory ' => application_path. '/controllers ',),)
;

The "Frontcontroller" resource is a special case. His options are quite special.

Whether it's using your own resource plug-in for writing or using a Third-party resource plug-in. You have to make sure Bootstrap can find them, bootstrap. Internal Zend_loader_pluginloader allows us to specify the class prefix for the resource plug-in, and the resource plug-in can be easily registered by the classpath of the resource class.

For example, if you write a resource plug-in that is stored under application_path/resources/, the class prefix is my_resource. You can register the load by using the following methods:

$application = new Zend_application (application_env, Array (
  ' pluginpaths ' => array (
    ' My_resource ' => Application_path. '/resources/',
  ),
  ' Resources ' => array ('
    frontcontroller ' => Array (
      ' controllerdirectory ' = > Application_path. '/controllers ',),)
;

In an application, you can use resources in the specified directory.

Similar to resource methods, you can load a resource plug-in by using the bootstrap () method. Load 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 Registration Form

In order to avoid duplication of resources, resulting in unnecessary waste zend_application_bootstrap_bootstrapabstract Provides a local registry object to store these resource objects. When you want to store a resource, you just need to return the resource in the method.

For flexibility, the registry exists as an internal "container". objects can be stored in the container as long as they are. The resource name corresponds to the container's properties. By default, you can use Zend_registry to get instances, or you can customize other objects. The Setcontainer () and GetContainer () method can be used to manipulate the container itself. GetResource ($resource) can be used to get a specified resource. Hasresource ($resource) to check if a resource is already 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 actions:

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

Please note that the registry container is not global. This means that you need to access the bootstrap to get the resources. Zend_application_bootstrap_bootstrap provides run (), after run (), it registers as "Bootstrap" of the front-end controller parameters, through which he can obtain routers, distributors, Plug-ins, and motion controllers.

The specific use method:

Class Foocontroller extends zend_controller_action
{public
  function init ()
  {
    $bootstrap = $this-> Getinvokearg (' bootstrap ');
    $view = $bootstrap->getresource (' view ');
    // ...
  }
}

To prevent duplicate enrollment from 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 earlier, all resources-either methods or Plug-ins-are run through Bootstrap ($resource), where $resource is the name of the resource, or an array of resource names, or null, which indicates that all resources are loaded to run.

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


More interested in Zend related content readers can view the site topics: "The introduction of the Zend Framework frame", "PHP Excellent Development Framework Summary", "Yii framework Introduction and common skills Summary", "thinkphp Introductory Course", "PHP object-oriented Programming Program , "Php+mysql Database operation Introduction Tutorial" and "PHP common database Operation Skills Summary"

I hope this article will help you with the PHP program design.

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.