Detailed explanation of Application and Bootstrap usage in Zend Framework tutorial, zendbootstrap_PHP tutorial

WBOY
Release: 2016-07-12 08:57:30
Original
829 people have browsed it

Detailed explanation of Application and Bootstrap usage in Zend Framework tutorial, zendbootstrap

This article explains the usage of Application and Bootstrap in Zend Framework tutorial with examples. Share it with everyone for your reference, the details are as follows:

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

Zend_Application usage can be subdivided into three types:

Zend_Application: Loads the PHP environment, including include_paths and automatic loading, and instantiates the boot class.

Zend_Application_Bootstrap: Provides an interface for boot classes.

Zend_Application_Bootstrap_Bootstrap completes most of the common functions that booting needs to provide, including dependency checking and loading boot resources on demand.

Zend_Application_Resource provides on-demand resource loading function

Developers can inherit Zend_Application_Bootstrap_Bootstrap or implement the Zend_Application_Bootstrap_Bootstrapper interface as needed. Zend_Application is loaded in the entry file (for example, public/index.php) and instantiated according to the boot options and current environment configuration.

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

Required include_paths

Autoloading function additionally loads registered namespaces

php.ini initialization settings

Specify the bootstrap class name, if it is not "Bootstrap"

The prefix key-value pair of the resource represents 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 a specified location

Bootloader

The second function of Zend_Application is to bootstrap applications. 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();
}

Copy after login

The api mainly provides environment configuration, obtaining bootloading resources, and bootloader

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

Resource methods

The resource method that implements the Zend_Application_Bootstrap_BootstrapAbstract interface must follow the following rules. The method type is protected, and the prefix of the method must start with _init will.

If you want to load and use a resource method, just add the resource name in bootstrap(). The resource name is the resource method without the _init prefix.

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

For example bootstrap class:

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

Copy after login

Only load using _initFoo() :

$bootstrap->bootstrap('foo');

Copy after login

Load using _initFoo() and _initBar() :

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

Copy after login

Loading uses all resource methods, using bootstrap() without parameters:

$bootstrap->bootstrap();

Copy after login

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
| │            └── index
│             └── index.phtml
├── docs
│ └── README.txt
├── library
├── public
│ └── index.php
└── tests
├── application
│ └── controllers
│ └── IndexControllerTest.php
├── bootstrap.php
├── library
└── phpunit.xml
16 directories, 11 files

Newer versions of zend framework introduce Zend_Application and Bootstrap. Zend_Application provides a bootstrap of reusable resources, generic and modular bootstrap classes and dependency checks. It is also responsible for setting PHP environment variables and automatic loading functions by default.

默认新建项目后,会给出如下的几个文件:

1.项目的Bootstrap

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

具体代码如下:

<&#63;php
class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
{
}

Copy after login

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

Copy after login

3.项目入口文件

├── public
│ └── index.php

<&#63;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') &#63; 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();

Copy after login

以上代码就是基本的使用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();
}

Copy after login

例如

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

Copy after login

加载使用资源插件

我了提供资源的重用性,可以将资源方法定义为资源插件。。

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

Copy after login

采用资源插件,不仅可以让资源可以重复利用,同时让bootstrap更简洁,如果要修改,新增资源也无需修改你的bootstrap。

通过实现Zend_Application_Bootstrap_BootstrapAbstract (被 Zend_Application_Bootstrap_Bootstrap 继承) ,才可以使用定义的资源插件

通过将指定的选项传递到application object and/or bootstrap,来注册使用资源插件。这些选项可能会从一个配置文件,或通过手动指定。规则是选项​​必须是键值对,键代表资源名称。资源名称,是资源插件类的类前缀。例如,Zend框架自带的资源类前缀“Zend_Application_Resource_”;任何以下,这都是资源的名称。例如,

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

Copy after login

"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',
    ),
  ),
));

Copy after login

在应用程序中比可以使用指定目录下的资源。

和资源方法类似,通过使用 the bootstrap() 方法可以加载资源插件。加载单一,多个,全部的资源插件的配置方式也类似.

例如:

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

Copy after login

资源注册表

为了避免资源的重复注册,导致不必要的浪费Zend_Application_Bootstrap_BootstrapAbstract 提供了一个本地注册表对象存储这些资源对象.当你想要存放一个资源的时候,只需要在方法中返回这个资源即可。

为了灵活性,注册表是作为一个内部“容器”存在的。只要是对象都可以存入到容器中。资源名称对应为容器的属性。默认情况下,可以通过Zend_Registry获取实例使用,也可以自定义其他对象。 setContainer() and getContainer() 方法可用于操纵容器本身。getResource($resource) 可用于获取一个指定资源。hasResource($resource) 可以检查资源是否已经注册存在

例如,注册一个view资源:

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

Copy after login

资源的相关操作:

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

Copy after login

请注意:注册表容器是不是全局的。这意味着你需要通过访问的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');
    // ...
  }
}

Copy after login

为了防止重复注册加载资源方法和插件或一些资源可能依赖于其他资源。为了解决这两个问题,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;
  }
}

Copy after login

更多关于zend相关内容感兴趣的读者可查看本站专题:《Zend FrameWork框架入门教程》、《php优秀开发框架总结》、《Yii框架入门及常用技巧总结》、《ThinkPHP入门教程》、《php面向对象程序设计入门教程》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总》

I hope this article will be helpful to everyone in PHP programming.

Articles you may be interested in:

  • Analysis of configuration file application.ini in Zend Framework tutorial
  • Detailed explanation of Loader and PluginLoader usage in Zend Framework tutorial
  • Detailed explanation of Autoloading usage in Zend Framework tutorial
  • Resource Autoloading usage example in Zend Framework tutorial
  • Analysis of Controller usage in MVC framework in Zend Framework tutorial
  • The road to Zend Framework tutorial is based on the function Zend_Controller_Router Detailed explanation
  • Zend Framework tutorial: Detailed explanation of the usage of the Zend_Controller_Plugin plug-in
  • Zend Framework tutorial: Detailed explanation of the encapsulation of the response object Zend_Controller_Response instance
  • Zend Framework tutorial: Detailed explanation of the encapsulation of the request object Zend_Controller_Request instance
  • Detailed explanation of Zend Framework tutorial’s action base class Zend_Controller_Action
  • Zend Framework tutorial’s detailed explanation of usage of distributor Zend_Controller_Dispatcher
  • Zend Framework tutorial detailed explanation of usage of front-end controller Zend_Controller_Front

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/1108610.htmlTechArticleDetailed explanation of Application and Bootstrap usage in Zend Framework tutorial, zendbootstrap This article explains the usage of Application and Bootstrap in Zend Framework tutorial. Sharing it with everyone for your reference,...
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template