Previous Next

Theory of Operation

Getting an MVC application configured and ready to dispatch has required an increasing amount of code as more features become available: setting up the database, configuring your view and view helpers, configuring your layouts, registering plugins, registering action helpers, and more.

Additionally, you will often want to reuse the same code to bootstrap your tests, a cronjob, or a service script. While it's possible to simply include your bootstrap script, oftentimes there are initializations that are environment specific – you may not need the MVC for a cronjob, or just the DB layer for a service script.

Zend_Application aims to make this easier and to promote reuse by encapsulating bootstrapping into OOP paradigms.

Zend_Application is broken into three realms:

  • Zend_Application: loads the PHP environment, including include_paths and autoloading, and instantiates the requested bootstrap class.

  • Zend_Application_Bootstrap: provides interfaces for bootstrap classes. Zend_Application_Bootstrap_Bootstrap provides common functionality for most bootstrapping needs, including dependency checking algorithms and the ability to load bootstrap resources on demand.

  • Zend_Application_Resource provides an interface for standard bootstrapping resources that can be loaded on demand by a bootstrap instance, as well as several default resource implementations.

Developers create a bootstrap class for their application, extending Zend_Application_Bootstrap_Bootstrap or implementing (minimally) Zend_Application_Bootstrap_Bootstrapper. The entry point (e.g., public/index.php) will load Zend_Application, and instantiate it by passing:

  • The current environment

  • Options for bootstrapping

The bootstrap options include the path to the file containing the bootstrap class and optionally:

  • Any extra include_paths to set

  • Any additional autoloader namespaces to register

  • Any php.ini settings to initialize

  • The class name for the bootstrap class (if not "Bootstrap")

  • Resource prefix to path pairs to use

  • Any resources to use (by class name or short name)

  • Additional path to a configuration file to load

  • Additional configuration options

Options may be an array, a Zend_Config object, or the path to a configuration file.

Bootstrapping

Zend_Application's second area of responsibility is executing the application bootstrap. Bootstraps minimally need to implement Zend_Application_Bootstrap_Bootstrapper, which defines the following 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();
}

This API allows the bootstrap to accept the environment and configuration from the application object, report the resources its responsible for bootstrapping, and then bootstrap and run the application.

You can implement this interface on your own, extend Zend_Application_Bootstrap_BootstrapAbstract, or use Zend_Application_Bootstrap_Bootstrap.

Besides this functionality, there are a number of other areas of concern you should familiarize yourself with.

Resource Methods

The Zend_Application_Bootstrap_BootstrapAbstract implementation provides a simple convention for defining class resource methods. Any protected method beginning with a name prefixed with _init will be considered a resource method.

To bootstrap a single resource method, use the bootstrap() method, and pass it the name of the resource. The name will be the method name minus the _init prefix.

To bootstrap several resource methods, pass an array of names. Too bootstrap all resource methods, pass nothing.

Take the following bootstrap class:

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

    protected function _initBar()
    {
        // ...
    }

    protected function _initBaz()
    {
        // ...
    }
}

To bootstrap just the _initFoo() method, do the following:

$bootstrap->bootstrap('foo');

To bootstrap the _initFoo() and _initBar() methods, do the following:

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

To bootstrap all resource methods, call bootstrap() with no arguments:

$bootstrap->bootstrap();

Bootstraps that use resource plugins

To make your bootstraps more re-usable, we have provided the ability to push your resources into resource plugin classes. This allows you to mix and match resources simply via configuration. We will cover how to create resources later; in this section we will show you how to utilize them only.

If your bootstrap should be capable of using resource plugins, you will need to implement an additional interface, Zend_Application_Bootstrap_ResourceBootstrapper. This interface defines an API for locating, registering, and loading resource plugins:

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

Resource plugins basically provide the ability to create resource intializers that can be re-used between applications. This allows you to keep your actual bootstrap relatively clean, and to introduce new resources without needing to touch your bootstrap itself.

Zend_Application_Bootstrap_BootstrapAbstract (and Zend_Application_Bootstrap_Bootstrap by extension) implement this interface as well, allowing you to utilize resource plugins.

To utilize resource plugins, you must specify them in the options passed to the application object and/or bootstrap. These options may come from a configuration file, or be passed in manually. Options will be of key to options pairs, with the key representing the resource name. The resource name will be the segment following the class prefix. For example, the resources shipped with Zend Framework have the class prefix "Zend_Application_Resource_"; anything following this would be the name of the resource. As an example,

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

This indicates that the "FrontController" resource should be used, with the options specified.

If you begin writing your own resource plugins, or utilize third-party resource plugins, you will need to tell your bootstrap where to look for them. Internally, the bootstrap utilizes Zend_Loader_PluginLoader, so you will only need to indicate the common class prefix an path pairs.

As an example, let's assume you have custom resource plugins in APPLICATION_PATH/resources/ and that they share the common class prefix of My_Resource. You would then pass that information to the application object as follows:

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

You would now be able to use resources from that directory.

Just like resource methods, you use the bootstrap() method to execute resource plugins. Just like with resource methods, you can specify either a single resource plugin, multiple plugins (via an array), or all plugins. Additionally, you can mix and match to execute resource methods as well.

// Execute one:
$bootstrap->bootstrap('FrontController');

// Execute several:
$bootstrap->bootstrap(array('FrontController', 'Foo'));

// Execute all resource methods and plugins:
$bootstrap->bootstrap();

Resource Registry

Many, if not all, of your resource methods or plugins will initialize objects, and in many cases, these objects will be needed elsewhere in your application. How can you access them?

Zend_Application_Bootstrap_BootstrapAbstract provides a local registry for these objects. To store your objects in them, you simply return them from your resources.

For maximum flexibility, this registry is referred to as a "container" internally; its only requirements are that it is an object. Resources are then registered as properties named after the resource name. By default, an instance of Zend_Registry is used, but you may also specify any other object you wish. The methods setContainer() and getContainer() may be used to manipulate the container itself. getResource($resource) can be used to fetch a given resource from the container, and hasResource($resource) to check if the resource has actually been registered.

As an example, consider a basic view resource:

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

        return $view;
    }
}

You can then check for it and/or fetch it as follows:

// 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 and also the container is not global. This means that you need access to the bootstrap in order to fetch resources. Zend_Application_Bootstrap_Bootstrap provides some convenience for this: during its run() execution, it registers itself as the front controller parameter "bootstrap", which allows you to fetch it from the router, dispatcher, plugins, and action controllers.

As an example, if you wanted access to the view resource from above within your action controller, you could do the following:

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

Dependency Tracking

In addition to executing resource methods and plugins, it's necessary to ensure that these are executed once and once only; these are meant to bootstrap an application, and executing multiple times can lead to resource overhead.

At the same time, some resources may depend on other resources being executed. To solve these two issues, Zend_Application_Bootstrap_BootstrapAbstract provides a simple, effective mechanism for dependency tracking.

As noted previously, all resources -- whether methods or plugins -- are bootstrapped by calling bootstrap($resource), where $resource is the name of a resource, an array of resources, or, left empty, indicates all resources should be run.

If a resource depends on another resource, it should call bootstrap() within its code to ensure that resource has been executed. Subsequent calls to it will then be ignored.

In a resource method, such a call would look like this:

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

Resource Plugins

As noted previously, a good way to create re-usable bootstrap resources and to offload much of your coding to discrete classes is to utilize resource plugins. While Zend Framework ships with a number of standard resource plugins, the intention is that developers should write their own to encapsulate their own initialization needs.

Resource plugins need only implement Zend_Application_Resource_Resource, or, more simply still, extend Zend_Application_Resource_ResourceAbstract. The basic interface is simply this:

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

The interface defines simply that a resource plugin should accept options to the constructor, have mechanisms for setting and retrieving options, have mechanisms for setting and retrieving the bootstrap object, and an initialization method.

As an example, let's assume you have a common view intialization you use in your applications. You have a common doctype, CSS and JavaScript, and you want to be able to pass in a base document title via configuration. Such a resource plugin might look like this:

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

As long as you register the prefix path for this resource plugin, you can then use it in your application. Even better, because it uses the plugin loader, you are effectively overriding the shipped "View" resource plugin, ensuring that your own is used instead.

Previous Next
Introduction to Zend Framework
概要
インストール
Zend_Acl
導入
アクセス制御の洗練
高度な使用法
Zend_Amf
導入
Zend_Amf_Server
Zend_Application
導入
Zend_Application クイックスタート
Theory of Operation
コア機能
利用できるリソースプラグイン
Zend_Auth
導入
データベースのテーブルでの認証
ダイジェスト認証
HTTP 認証アダプタ
LDAP 認証
Open ID 認証
Zend_Cache
導入
キャッシュの仕組み
Zend_Cache のフロントエンド
Zend_Cache のバックエンド
Zend_Captcha
導入
Captcha の方法
CAPTCHA アダプタ
Zend_CodeGenerator
導入
Zend_CodeGeneratorサンプル
Zend_CodeGeneratorリファレンス
Zend_Config
導入
動作原理
Zend_Config_Ini
Zend_Config_Xml
Zend_Config_Writer
Zend_Config_Writer
Zend_Console_Getopt
導入
Getopt の規則の宣言
オプションおよび引数の取得
Zend_Console_Getopt の設定
Zend_Controller
Zend_Controller クイックスタート
Zend_Controller の基本
フロントコントローラ
リクエストオブジェクト
標準のルータ
ディスパッチャ
アクションコントローラ
アクションヘルパー
レスポンスオブジェクト
プラグイン
モジュラーディレクトリ構造の規約の使用
MVC での例外
以前のバージョンからの移行
Zend_Currency
Zend_Currency について
通貨の操作方法
以前のバージョンからの移行
Zend_Date
導入
動作原理
基本メソッド
Zend_Date API の概要
日付の作成
日付関数全般用の定数
動作例
Zend_Db
Zend_Db_Adapter
Zend_Db_Statement
Zend_Db_Profiler
Zend_Db_Select
Zend_Db_Table
Zend_Db_Table_Row
Zend_Db_Table_Rowset
導入
Zend_Db_Table_Definition
Zend_Debug
変数の出力
Zend_Dojo
導入
Zend_Dojo_Data: dojo.data エンベロープ
Dojo ビューヘルパー
Dojoフォーム要素とデコレーター
Zend_Dojo build layer support
Zend_Dom
導入
Zend_Dom_Query
Zend_Exception
例外の使用法
Zend_Feed
導入
フィードの読み込み
ウェブページからのフィードの取得
RSS フィードの使用
Atom フィードの使用
単一の Atom エントリの処理
フィードおよびエントリの構造の変更
独自のフィードクラスおよびエントリクラス
Zend_Feed_Reader
Zend_File
Zend_File_Transfer
Zend_File_Transfer 用のバリデータ
Filters for Zend_File_Transfer
以前のバージョンからの移行
Zend_Filter
導入
標準のフィルタクラス群
フィルタチェイン
フィルタの書き方
Zend_Filter_Input
Zend_Filter_Inflector
前バージョンからの移行
Zend_Form
Zend_Form
Zend_Form クイックスタート
Zend_Form_Element を用いたフォーム要素の作成
Zend_Form によるフォームの作成
Zend_Form_Decorator による独自のフォームマークアップの作成
Zend Framework に同梱されている標準のフォーム要素
Zend Framework に同梱されている標準のデコレータ
Zend_Form の国際化
Zend_Form の高度な使用法
Zend_Gdata
導入
AuthSub による認証
Using the Book Search Data API
ClientLogin による認証
Google Calendar の使用法
Google Documents List Data API の使用法
Using Google Health
Google Spreadsheets の使用法
Google Apps Provisioning の使用法
Google Base の使用法
Picasa Web Albums の使用法
YouTube Data API の使用法
Gdata の例外処理
Zend_Http
導入
Zend_Http_Client - 高度な使用法
Zend_Http_Client - 接続アダプタ
前バージョンからの移行
Zend_Http_Cookie および Zend_Http_CookieJar
Zend_Http_Response
Zend_InfoCard
導入
Zend_Json
導入
基本的な使用法
Zend_Json の高度な使用法
XML から JSON への変換
Zend_Json_Server - JSON-RPCサーバー
Zend_Layout
導入
Zend_Layout クイックスタート
Zend_Layout の設定オプション
Zend_Layout の高度な使用法
Zend_Ldap
導入
API概要
利用シナリオ
ツール
Zend_Ldap_Nodeを使用してLDAPツリーへのオブジェクト指向アクセス
LDAPサーバから情報を取得
LDIFへ、または、からのLDAPデータシリアライズ
Zend_Loader
ファイルやクラスの動的な読み込み
The Autoloader
Resource Autoloaders
プラグインのロード
Zend_Locale
導入
Zend_Locale の使用法
正規化および地域化
日付および時刻の扱い
サポートするロケール
以前のバージョンからの移行
Zend_Log
概要
ライター
フォーマッタ
フィルタ
Zend_Mail
導入
SMTP 経由での送信
SMTP 接続による複数のメールの送信
異なる転送手段の使用
HTML メール
ファイルの添付
受信者の追加
MIME バウンダリの制御
追加のヘッダ
文字セット
エンコーディング
SMTP 認証
セキュアな SMTP トランスポート
メールメッセージの読み込み
Zend_Measure
導入
計測値の作成
計測値の出力
計測値の操作
計測値の型
Zend_Memory
概要
メモリマネージャ
メモリオブジェクト
Zend_Mime
Zend_Mime
Zend_Mime_Message
Zend_Mime_Part
Zend_Navigation
導入
画面
Containers
Migrating from Previous Versions
Zend_OpenId
導入
Zend_OpenId_Consumer の基本
Zend_OpenId_Provider
Zend_Paginator
導入
使用法
設定
高度な使用法
Zend_Pdf
導入
PDF ドキュメントの作成および読み込み
PDF ドキュメントへの変更内容の保存
ページの操作
描画
Interactive Features
ドキュメントの情報およびメタデータ
Zend_Pdf モジュールの使用例
Zend_ProgressBar
Zend_ProgressBar
Zend_Queue
導入
使用例
フレームワーク
アダプタ
Zend_Queueのカスタマイズ
Stomp
Zend_Reflection
導入
Zend_Reflectionサンプル
Zend_Reflectionリファレンス
Zend_Registry
レジストリの使用法
Zend_Rest
導入
Zend_Rest_Client
Zend_Rest_Server
Zend_Search_Lucene
概要
インデックスの構築
インデックスの検索
クエリ言語
クエリ作成用の API
文字セット
拡張性
Java Lucene との相互運用
応用
ベストプラクティス
Zend_Server
導入
Zend_Server_Reflection
Zend_Service
導入
Zend_Service_Akismet
Zend_Service_Amazon
Zend_Service_Amazon_Ec2
Zend_Service_Amazon_Ec2: Instances
Zend_Service_Amazon_Ec2: Windows Instances
Zend_Service_Amazon_Ec2: Reserved Instances
Zend_Service_Amazon_Ec2: CloudWatch Monitoring
Zend_Service_Amazon_Ec2: Amazon Machine Images (AMI)
Zend_Service_Amazon_Ec2: Elastic Block Stroage (EBS)
Zend_Service_Amazon_Ec2: Elastic IP Addresses
Zend_Service_Amazon_Ec2: Keypairs
Zend_Service_Amazon_Ec2:リージョンおよび利用可能ゾーン
Zend_Service_Amazon_Ec2: Security Groups
Zend_Service_Amazon_S3
Zend_Service_Amazon_Sqs
Zend_Service_Audioscrobbler
Zend_Service_Delicious
Zend_Service_Flickr
Zend_Service_Nirvanix
Zend_Service_ReCaptcha
Zend_Service_Simpy
導入
Zend_Service_StrikeIron
Zend_Service_StrikeIron: バンドルされているサービス
Zend_Service_StrikeIron: 応用編
Zend_Service_Technorati
Zend_Service_Twitter
Zend_Service_Yahoo
Zend_Session
導入
基本的な使用法
高度な使用法
グローバルセッションの管理
Zend_Session_SaveHandler_DbTable
Zend_Soap
Zend_Soap_Server
Zend_Soap_Client
WSDLアクセッサ
自動検出
Zend_Tag
導入
Zend_Tag_Cloud
Zend_Test
導入
Zend_Test_PHPUnit
Zend_Test_PHPUnit_Db
Zend_Text
Zend_Text_Figlet
Zend_Text_Table
Zend_TimeSync
導入
Zend_TimeSync の動作
Zend_Tool_Framework
導入
CLIツールの使用
アーキテクチャ
Zend_Tool_Frameworkを利用してプロバイダを作成する
出荷されたシステムプロバイダー
Extending and Configuring Zend_Tool_Framework
Zend_Tool_Project
導入
プロジェクトを作成
Zend Toolプロジェクトプロバイダー
Zend_Translate
導入
Zend_Translate のアダプタ
翻訳アダプタの使用法
ソースファイルの作成
翻訳用の追加機能
Plural notations for Translation
以前のバージョンからの移行
Zend_Uri
Zend_Uri
Zend_Validate
導入
標準のバリデーションクラス群
バリデータチェイン
バリデータの書き方
検証メッセージ
Zend_Version
Zend Framework のバージョンの取得
Zend_View
導入
コントローラスクリプト
ビュースクリプト
ビューヘルパー
Zend_View_Abstract
以前のバージョンからの移行
Zend_Wildfire
Zend_Wildfire
Zend_XmlRpc
導入
Zend_XmlRpc_Client
Zend_XmlRpc_Server
Zend Framework のシステム要件
導入
Zend Framework PHP 標準コーディング規約
概要
PHP ファイルの書式
命名規約
コーディングスタイル
Zend Framework Documentation Standard
Overview
Documentation File Formatting
Recommendations
Zend Framework MVC アプリケーションのために推奨されるプロジェクト構造
概要
推奨されるプロジェクト・ディレクトリ構造
モジュール構造
リライト設定ガイド
Zend Framework Performance Guide
導入
クラスの読み込み
Zend_Dbパフォーマンス
国際化(i18n)とローカライズ(l10n)
ビューのレンダリング
著作権に関する情報