>  기사  >  php教程  >  Zend Framework 튜토리얼의 애플리케이션 및 부트스트랩 사용법에 대한 자세한 설명

Zend Framework 튜토리얼의 애플리케이션 및 부트스트랩 사용법에 대한 자세한 설명

高洛峰
高洛峰원래의
2016-12-27 14:36:281379검색

이 기사의 예에서는 Zend Framework 튜토리얼에서 애플리케이션과 부트스트랩의 사용법을 설명합니다. 참고할 수 있도록 다음과 같이 모든 사람과 공유하세요.

MVC 애플리케이션에서는 데이터베이스 링크를 초기화 및 설정하고, 뷰 및 뷰 어시스턴트를 구성하고, 레이아웃을 구성하고, 관련 플러그인을 등록하고, 액션 어시스턴트를 등록해야 합니다. 등 구성 및 준비 작업을 하나씩 완료해야 합니다. 때로는 일부 초기화 작업이 필요할 수도 있지만 어떤 경우에는 이러한 초기화가 필요하지 않을 수도 있습니다. Zend_Application은 이러한 작업을 완료할 수 있을 뿐만 아니라 이러한 구성 및 초기화 작업을 보다 통합되고 질서 있게 만들어 재사용성을 높일 수 있습니다.

Zend_Application 사용법은 세 가지 유형으로 나눌 수 있습니다.

Zend_Application: include_paths 및 자동 로딩을 포함하여 PHP 환경을 로드하고 부팅 클래스를 인스턴스화합니다.

Zend_Application_Bootstrap: 부팅 클래스에 대한 인터페이스를 제공합니다.

Zend_Application_Bootstrap_Bootstrap은 종속성 확인 및 요청 시 부팅 리소스 로드를 포함하여 부팅에서 제공해야 하는 가장 일반적인 기능을 완성합니다.

Zend_Application_Resource는 온디맨드 리소스 로딩 기능을 제공합니다

개발자는 필요에 따라 Zend_Application_Bootstrap_Bootstrap을 상속하거나 Zend_Application_Bootstrap_Bootstrapper 인터페이스를 구현할 수 있습니다. Zend_Application은 항목 파일(예: public/index.php)에 로드되고 부팅 옵션 및 현재 환경 구성에 따라 인스턴스화됩니다.

부팅 옵션에는 지정된 부팅 클래스 파일과 부팅 클래스 경로가 포함됩니다. 옵션은 다음과 같습니다.

필수 include_paths

자동 로딩 기능은 등록된 네임스페이스를 추가로 로드합니다

php.ini 초기화 설정

"Bootstrap"이 아닌 경우 부트스트랩 클래스 이름 지정

리소스의 접두사 키-값 쌍은 리소스 접두사 이름을 나타냅니다

리소스 클래스 이름 또는 별칭

추가로 로드된 구성 파일 경로

추가 구성 옵션

옵션은 배열, Zend_Config 개체 또는 지정된 위치의 구성 파일

Bootstrapper

Zend_Application의 두 번째 기능은 애플리케이션을 안내하는 것입니다. Bootstrap은 Zend_Application_Bootstrap_Bootstrapper 인터페이스를 구현해야 합니다.

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

api는 주로 환경 구성을 제공합니다.

인터페이스를 구현하거나 Zend_Application_Bootstrap_BootstrapAbstract 또는 Zend_Application_Bootstrap_Bootstrap을 상속할 수 있습니다.

리소스 메서드

리소스 메서드 Zend_Application_Bootstrap_BootstrapAbstract 인터페이스를 구현하는 메서드는 다음 규칙을 따라야 합니다. 메서드 유형은 보호되며 메서드의 접두사는 _init로 시작해야 합니다.

리소스 메서드를 로드하여 사용하려면 리소스를 추가하기만 하면 됩니다. bootstrap()의 이름입니다. 리소스 이름은 리소스 메서드이며 _init 접두사를 제거합니다.

여러 리소스 메소드를 로드하려는 경우 배열을 통해 지정할 수 있습니다.

예를 들어 부트스트랩 클래스는 다음과 같습니다.

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
│ ├── 컨트롤러
│ │ ├── ErrorController.php
│ │ └── IndexController.php
│ ├── 모델
│ └── 뷰
│ ├ ── 헬퍼
│  └── 스크립트
│  ├── error
│  └── error.phtml
│               └── index.phtml
├ ── docs
│ └── README.txt
├── 라이브러리
├── 공개
│ └── index.php
└── 테스트
├── 애플리케이션
│ └─ ─ 컨트롤러
│ └── IndexControllerTest.php
├── bootstrap.php
├── 라이브러리
└── phpunit.xml
16개, 11개 파일

최신 버전의 zend 프레임워크에는 Zend_Application 및 Bootstrap이 도입되었습니다. Zend_Application은 재사용 가능한 리소스의 부트스트랩, 일반 및 모듈식 부트스트랩 클래스 및 종속성 검사를 제공합니다. 또한 기본적으로 PHP 환경 변수 및 자동 로딩 기능을 설정하는 역할도 담당합니다.

기본적으로 새 프로젝트를 생성하면 다음 파일이 제공됩니다.

1. 프로젝트의 부트스트랩

first_web/

├── application
│ ├── Bootstrap.php

구체 코드는 다음과 같습니다.

<?php
class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
{
}
구성 파일

│   ├── 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(&#39;APPLICATION_PATH&#39;)
  || define(&#39;APPLICATION_PATH&#39;, realpath(dirname(__FILE__) . &#39;/../application&#39;));
// Define application environment
defined(&#39;APPLICATION_ENV&#39;)
  || define(&#39;APPLICATION_ENV&#39;, (getenv(&#39;APPLICATION_ENV&#39;) ? getenv(&#39;APPLICATION_ENV&#39;) : &#39;production&#39;));
// Ensure library/ is on include_path
set_include_path(implode(PATH_SEPARATOR, array(
  realpath(APPLICATION_PATH . &#39;/../library&#39;),
  get_include_path(),
)));
/** Zend_Application */
require_once &#39;Zend/Application.php&#39;;
// Create application, bootstrap, and run
$application = new Zend_Application(
  APPLICATION_ENV,
  APPLICATION_PATH . &#39;/configs/application.ini&#39;
);
$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  = &#39;&#39;;
      if (array_key_exists(&#39;title&#39;, $options)) {
        $title = $options[&#39;title&#39;];
        unset($options[&#39;title&#39;]);
      }
      $view = new Zend_View($options);
      $view->doctype(&#39;XHTML1_STRICT&#39;);
      $view->headTitle($title);
      $view->headLink()->appendStylesheet(&#39;/css/site.css&#39;);
      $view->headScript()->appendfile(&#39;/js/analytics.js&#39;);
      $viewRenderer =
        Zend_Controller_Action_HelperBroker::getStaticHelper(
          &#39;ViewRenderer&#39;
        );
      $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 object and/or bootstrap,来注册使用资源插件。这些选项可能会从一个配置文件,或通过手动指定。规则是选项必须是键值对,键代表资源名称。资源名称,是资源插件类的类前缀。例如,Zend框架自带的资源类前缀“Zend_Application_Resource_”;任何以下,这都是资源的名称。例如,

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

"FrontController"资源是个特例。他的选项比较特殊。

无论是使用自己的写的资源插件还是使用第三方的资源插件。你必须保证bootstrap能找到他们,bootstrap 内部通过 Zend_Loader_PluginLoader可以让我们只需要指定资源插件的类前缀,值为资源类的类路径便可以轻松注册资源插件。

例如,如果编写的资源插件存放在APPLICATION_PATH/resources/ 下,类前缀为My_Resource. 可以使用如下方法注册加载:

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

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

和资源方法类似,通过使用 the 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() 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;
  }
}

资源的相关操作:

// Using the has/getResource() pair:
if ($bootstrap->hasResource(&#39;view&#39;)) {
  $view = $bootstrap->getResource(&#39;view&#39;);
}
// 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(&#39;bootstrap&#39;);
    $view = $bootstrap->getResource(&#39;view&#39;);
    // ...
  }
}

为了防止重复注册加载资源方法和插件或一些资源可能依赖于其他资源。为了解决这两个问题,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(&#39;FrontController&#39;);
    // Retrieve the front controller from the bootstrap registry
    $front = $this->getResource(&#39;FrontController&#39;);
    $request = new Zend_Controller_Request_Http();
    $request->setBaseUrl(&#39;/foo&#39;);
    $front->setRequest($request);
    // Ensure the request is stored in the bootstrap registry
    return $request;
  }
}

希望本文所述对大家PHP程序设计有所帮助。

更多Zend Framework教程之Application和Bootstrap用法详解相关文章请关注PHP中文网!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.