Previous Next

Class Loading

Anyone who ever performs profiling of a Zend Framework application will immediately recognize that class loading is relatively expensive in Zend Framework. Between the sheer number of class files that need to be loaded for many components, to the use of plugins that do not have a 1:1 relationship between their class name and the filesystem, the various calls to include_once and require_once can be problematic. This chapter intends to provide some concrete solutions to these issues.

How can I optimize my include_path?

One trivial optimization you can do to increase the speed of class loading is to pay careful attention to your include_path. In particular, you should do four things: use absolute paths (or paths relative to absolute paths), reduce the number of include paths you define, have your Zend Framework include_path as early as possible, and only include the current directory path at the end of your include_path.

Use absolute paths

While this may seem a micro-optimization, the fact is that if you don't, you'll get very little benefit from PHP's realpath cache, and as a result, opcode caching will not perform nearly as you may expect.

There are two easy ways to ensure this. First, you can hardcode the paths in your php.ini, httpd.conf, or .htaccess. Second, you can use PHP's realpath() function when setting your include_path:

$paths = array(
    realpath(dirname(__FILE__) . '/../library'),
    '.',
);
set_include_path(implode(PATH_SEPARATOR, $paths);

You can use relative paths -- so long as they are relative to an absolute path:

define('APPLICATION_PATH', realpath(dirname(__FILE__)));
$paths = array(
    APPLICATION_PATH . '/../library'),
    '.',
);
set_include_path(implode(PATH_SEPARATOR, $paths);

However, even so, it's typically a trivial task to simply pass the path to realpath().

Reduce the number of include paths you define

Include paths are scanned in the order in which they appear in the include_path. Obviously, this means that you'll get a result faster if the file is found on the first scan rather than the last. Thus, a rather obvious enhancement is to simply reduce the number of paths in your include_path to only what you need. Look through each include_path you've defined, and determine if you actually have any functionality in that path that is used in your application; if not, remove it.

Another optimization is to combine paths. For instance, Zend Framework follows PEAR naming conventions; thus, if you are using PEAR libraries (or libraries from another framework or component library that follows PEAR CS), try and put all of thse libraries on the same include_path. This can often be achieved by something as simple as symlinking one or more libraries into a common directory.

Define your Zend Framework include_path as early as possible

Continuing from the previous suggestion, another obvious optimization is to define your Zend Framework include_path as early as possible in your include_path. In most cases, it should be the first path in the list. This ensures that files included from Zend Framework are found on the first scan.

Define the current directory last, or not at all

Most include_path examples show using the current directory, or '.'. This is convenient for ensuring that scripts in the same directory as the file requiring them can be loaded. However, these same examples typically show this path item as the first item in the include_path -- which means that the current directory tree is always scanned first. In most cases, with Zend Framework applications, this is not desired, and the path may be safely pushed to the last item in the list.

Example #1 Example: Optimized include_path

Let's put all of these suggestions together. Our assumption will be that you are using one or more PEAR libraries in conjunction with Zend Framework -- perhaps the PHPUnit and Archive_Tar libraries -- and that you occasionally need to include files relative to the current file.

First, we'll create a library directory in our project. Inside that directory, we'll symlink our Zend Framework's library/Zend directory, as well as the necessary directories from our PEAR installation:

library
    Archive/
    PEAR/
    PHPUnit/
    Zend/

This allows us to add our own library code if necessary, while keeping shared libraries intact.

Next, we'll opt to create our include_path programmatically within our public/index.php file. This allows us to move our code around on the filesystem, without needing to edit the include_path every time.

We'll borrow ideas from each of the suggestions above: we'll use absolute paths, as determined using realpath(); we'll include the Zend Framework include path early; we've already consolidated include_paths; and we'll put the current directory as the last path. In fact, we're doing really well here -- we're going to end up with only two paths.

$paths = array(
    realpath(dirname(__FILE__) . '/../library'),
    '.'
);
set_include_path(implode(PATH_SEPARATOR, $paths));

How can I eliminate unnecessary require_once statements?

Lazy loading is an optimization technique designed to push the expensive operation of loading a class file until the last possible moment -- i.e., when instantiating an object of that class, calling a static class method, or referencing a class constant or static property. PHP supports this via autoloading, which allows you to define one or more callbacks to execute in order to map a class name to a file.

However, most benefits you may reap from autoloading are negated if your library code is still performing require_once calls -- which is precisely the case with Zend Framework. So, the question is: how can you eliminate those require_once calls in order to maximize autloader performance?

Strip require_once calls with find and sed

An easy way to strip require_once calls is to use the unix utilities 'find' and 'sed' in conjunction to comment out each call. Try executing the following statements (where '%' indicates the shell prompt):

% cd path/to/ZendFramework/library
% find . -name '*.php' -print0 | xargs -0 \
  sed --regexp-extended --in-place 's/(require_once)/\/\/ \1/g'

This one-liner (broken into two lines for readability) iterates through each PHP file and tells it to replace each instance of 'require_once' with '// require_once', effectively commenting out each such statement.

This command could be added to an automated build or release process trivially, helping boost performance in your production application. It should be noted, however, that if you use this technique, you must utilize autoloading; you can do that from your "public/index.php" file with the following code:

require_once 'Zend/Loader.php'; // one require_once is still necessary
Zend_Loader::registerAutoload();

How can I speed up plugin loading?

Many components have plugins, which allow you to create your own classes to utilize with the component, as well as to override existing, standard plugins shipped with Zend Framework. This provides important flexibility to the framework, but at a price: plugin loading is a fairly expensive task.

The plugin loader allows you to register class prefix / path pairs, allowing you to specify class files in non-standard paths. Each prefix can have multiple paths associated with it. Internally, the plugin loader loops through each prefix, and then through each path attached to it, testing to see if the file exists and is readable on that path. It then loads it, and tests to see that the class it is looking for is available. As you might imagine, this can lead to many stat calls on the filesystem.

Multiply this by the number of components that use the PluginLoader, and you get an idea of the scope of this issue. At the time of this writing, the following components made use of the PluginLoader:

  • Zend_Controller_Action_HelperBroker: helpers

  • Zend_Dojo: view helpers, form elements and decorators

  • Zend_File_Transfer: adapters

  • Zend_Filter_Inflector: filters (used by the ViewRenderer action helper and Zend_Layout)

  • Zend_Filter_Input: filters and validators

  • Zend_Form: elements, validators, filters, decorators, captcha and file transfer adapters

  • Zend_Paginator: adapters

  • Zend_View: helpers, filters

How can you reduce the number of such calls made?

Use the PluginLoader include file cache

Zend Framework 1.7.0 adds an include file cache to the PluginLoader. This functionality writes "include_once" calls to a file, which you can then include in your bootstrap. While this introduces extra include_once calls to your code, it also ensures that the PluginLoader returns as early as possible.

The PluginLoader documentation includes a complete example of its use.

Previous Next
Introduction to Zend Framework
概要
インストール
Zend_Acl
導入
アクセス制御の洗練
高度な使用法
Zend_Amf
導入
Zend_Amf_Server
Zend_Auth
導入
データベースのテーブルでの認証
ダイジェスト認証
HTTP 認証アダプタ
LDAP 認証
Open ID 認証
Zend_Cache
導入
キャッシュの仕組み
Zend_Cache のフロントエンド
Zend_Cache のバックエンド
Zend_Captcha
導入
Captcha の方法
Captcha アダプタ
Zend_Config
導入
動作原理
Zend_Config_Ini
Zend_Config_Xml
Zend_Config_Writer
Zend_Config_Writer
Zend_Console_Getopt
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_Debug
変数の出力
Zend_Dojo
導入
Zend_Dojo_Data: dojo.data エンベロープ
Dojo ビューヘルパー
Dojo Form Elements and Decorators
Zend_Dom
導入
Zend_Dom_Query
Zend_Exception
例外の使用法
Zend_Feed
導入
フィードの読み込み
ウェブページからのフィードの取得
RSS フィードの使用
Atom フィードの使用
単一の Atom エントリの処理
フィードおよびエントリの構造の変更
独自のフィードクラスおよびエントリクラス
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
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_Client - 接続アダプタ
Zend_Http_Cookie および Zend_Http_CookieJar
Zend_Http_Response
Zend_InfoCard
導入
Zend_Json
導入
基本的な使用法
JSON オブジェクト
XML から JSON への変換
Zend_Json_Server - JSON-RPC server
Zend_Layout
導入
Zend_Layout クイックスタート
Zend_Layout の設定オプション
Zend_Layout の高度な使用法
Zend_Ldap
導入
Zend_Loader
ファイルやクラスの動的な読み込み
プラグインのロード
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_OpenId
導入
Zend_OpenId_Consumer の基本
Zend_OpenId_Provider
Zend_Paginator
導入
使用法
設定
高度な使用法
Zend_Pdf
導入
PDF ドキュメントの作成および読み込み
PDF ドキュメントへの変更内容の保存
ドキュメントのページ
描画
ドキュメントの情報およびメタデータ
Zend_Pdf モジュールの使用例
Zend_ProgressBar
Zend_ProgressBar
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_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 Accessor
AutoDiscovery
Zend_Test
導入
Zend_Test_PHPUnit
Zend_Text
Zend_Text_Figlet
Zend_Text_Table
Zend_TimeSync
導入
Zend_TimeSync の動作
Zend_Translate
導入
Zend_Translate のアダプタ
翻訳アダプタの使用法
Migrating from previous versions
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 のシステム要件
PHP のバージョン
PHP の拡張モジュール
Zend Framework のコンポーネント
Zend Framework の依存性
Zend Framework PHP 標準コーディング規約
概要
PHP ファイルの書式
命名規約
コーディングスタイル
Zend Framework Performance Guide
Introduction
Class Loading
Internationalization (i18n) and Localization (l10n)
View Rendering
著作権に関する情報