(その3から続く)
Doctrine2との連携が確認できたところでひとまずDoctrineから離れてTwigとの連携を行うことにします。
Twigを公式サイトからDLして(2011/12/27現在最新版stableは1.4.0)Twig/をプロジェクトのlibrary/直下に持ってきます。
Zend Framework + Twigについてはいくつかの試みがネット上にありますが、今回は以下のライブラリを使うことにします。
https://github.com/benjamindulau/Ano_ZFTwig
※このライブラリはZend ApplicationによりTwigの設定を.iniファイルにまとめている点、および任意のviewヘルパーが使えることをきちんと明記している点が気に入ったので採用しました。
git clone https://github.com/benjamindulau/Ano_ZFTwig.git
で取得し、中のAno/をプロジェクトのlibrary/直下に持ってきます。
追加したライブラリをアプリケーションが読めるようにnamespaceを.iniファイルに追加します。
autoloaderNamespaces[] = "Twig_" autoloaderNamespaces[] = "Ano_"
pluginの登録をします。
pluginPaths.Ano_Application_Resource = APPLICATION_PATH "/../library/Ano/Application/Resource"
更にドキュメントに従って以下の設定を追加します。
resources.view.engines.php.class = "Ano_View_Engine_PhpEngine" resources.view.engines.php.viewSuffix = "phtml" resources.view.engines.twig.class = "Ano_ZFTwig_View_Engine_TwigEngine" resources.view.engines.twig.isDefault = 1 resources.view.engines.twig.viewSuffix = "twig" resources.view.engines.twig.options.charset = "utf-8" resources.view.engines.twig.options.strict_variables = 0 resources.view.engines.twig.options.cache = APPLICATION_PATH "/../var/cache/twig" resources.view.engines.twig.options.auto_escape = 1 resources.view.engines.twig.options.auto_reload = 1 resources.view.engines.twig.options.debug = 0 resources.view.engines.twig.options.trim_blocks = 1 resources.view.engines.twig.extensions.helper.class = "Ano_ZFTwig_Extension_HelperExtension" resources.view.engines.twig.extensions.trans.class = "Ano_ZFTwig_Extension_TransExtension"
※Twigのcacheを保存するディレクトリ(上記の設定では/path/to/project/var/cache/twig)をあらかじめプロジェクト内に作っておく必要があります。
さてここで、このライブラリを使ってTwigを使用する際にZend Layoutを使うかどうかの選択をしなければなりません。Zend_Layoutを使う場合にはTwigが持つ継承機能(extends)やblockが使えません。ドキュメントにはZend Layoutを使う場合/使わない場合それぞれの記述例が載っていますが、自分が試したところZend Layoutを使わずTwigの継承機能を使う場合はcacheが動作せず、ライブラリが提供しているappとzfという便利なグローバル変数も使えないという不具合があります。(githubで作者に報告していますが今のところガン無視されていますw)cacheが使えないと描画のパフォーマンスが悪くなるのは明らかなので今回はZend Layoutを使った方法を採用することにします。
zfコマンドを実行し、
zf enable layout
以下を.iniファイルに追加します。
resources.layout.layout = "layout" resources.layout.layoutPath = APPLICATION_PATH "/layouts/scripts/"
layoutファイルはこんな感じ
application/layouts/scripts/layout.twig
<head>
{{ headTitle() }}
{% meta, {'http-equiv': 'Content-Type', 'content': 'text/html; charset=utf-8'} %}
{% javascript 'js/jquery.js', {'mode': 'prepend'} %}
{% stylesheet 'css/layout.css', {'mode': 'prepend'} %}
<base href="{{ zf.serverUrl() }}/{{ zf.baseUrl() }}" />
{{ metas() }}
{{ javascripts() }}
{{ stylesheets() }}
</head>
<body>
{{ layoutBlock('content') }}
</body>errorコントローラー用のviewが無いと怒られてしまうのでこんな内容で作ります。
application/views/scripts/error/error.twig
<h1>An error occurred</h1> <h2>{{ error.code }}: {{ message }}</h2> {% if exception %} <h3>Exception information:</h3> <p> <b>Message:</b> {{ exception.message }}</p> <h3>Stack trace:</h3><pre>{{ exception.getTraceAsString() }}</pre> <h3>Request Parameters:</h3>{% for key, val in request.getParams() %}{{key}} => {{val}} {{', '}}{% endfor %} {% endif %}index.phtmlをindex.twigとリネームして内容をtwigで書き換えます。
application/views/scripts/index/index.twig
<!DOCTYPE HTML>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
findOneBy():</br>
{{name}}
</br></br>
findAll():</br>
{% for user in all_user %}
{{user.getName()}}</br>
{% endfor %}
</br>
ユーザ定義: </br>
{{second_user_name}}
</body>
</html>index.phpにアクセスして前回と同じ結果が表示されれば成功です。Zend_Viewを使った場合と比較してTwigを使えば非常にシンプルに記述できることが分かると思います。
プロジェクトの構造はこうなります。

application.iniです。
; -----------------------------; forked from https://github.com/guilhermeblanco/ZendFramework1-Doctrine2/blob/master/application/configs/application.ini; -----------------------------
[production]
; --------------------------; PHP Specific Configuration; --------------------------phpSettings.display_startup_errors = 0phpSettings.display_errors = 0
includePaths.library = APPLICATION_PATH "/../library"includePaths.models = APPLICATION_PATH "/models"
; ----------------------------------------; Zend Framework Application Configuration; ----------------------------------------bootstrap.path = APPLICATION_PATH "/Bootstrap.php"bootstrap.class = "Bootstrap"
pluginPaths.Bisna\Application\Resource\ = "Bisna/Application/Resource"pluginPaths.Ano_Application_Resource = APPLICATION_PATH "/../library/Ano/Application/Resource"
autoloaderNamespaces[] = BisnaautoloaderNamespaces[] = SymfonyautoloaderNamespaces[] = DoctrineautoloaderNamespaces[] = Kdf\EntityautoloaderNamespaces[] = "Twig_"autoloaderNamespaces[] = "Ano_"
; ------------------------------; Front Controller Configuration; ------------------------------
resources.frontController.controllerDirectory = APPLICATION_PATH "/controllers"resources.frontController.params.displayExceptions = 0
; ------------------------------------------------------------------------------; Doctrine Class Loader Configuration; ------------------------------------------------------------------------------
; ------------------------------------------------------------------------------; Doctrine Cache Configuration; ------------------------------------------------------------------------------
; Points to default cache instance to be used. Optional is only one cache is definedresources.doctrine.cache.defaultCacheInstance = default
; Cache Instance configuration for "default" cache;resources.doctrine.cache.instances.default.id = defaultresources.doctrine.cache.instances.default.adapterClass = "Doctrine\Common\Cache\MemcacheCache"
resources.doctrine.cache.instances.default.namespace = "Application_"resources.doctrine.cache.instances.default.options.servers.0.host = localhostresources.doctrine.cache.instances.default.options.servers.0.port = 11211;resources.doctrine.cache.instances.default.options.servers.0.persistent = true;resources.doctrine.cache.instances.default.options.servers.0.weight = 1;resources.doctrine.cache.instances.default.options.servers.0.timeout = 1;resources.doctrine.cache.instances.default.options.servers.0.retryInterval = 15;resources.doctrine.cache.instances.default.options.servers.0.status = true
; ------------------------------------------------------------------------------; Doctrine DBAL Configuration; ------------------------------------------------------------------------------
; Points to default connection to be used. Optional if only one connection is definedresources.doctrine.dbal.defaultConnection = default
; DBAL Connection configuration for "default" connection;resources.doctrine.dbal.connections.default.id = default;resources.doctrine.dbal.connections.default.eventManagerClass = "Doctrine\Common\EventManager";resources.doctrine.dbal.connections.default.eventSubscribers[] = "DoctrineExtensions\Sluggable\SluggableSubscriber";resources.doctrine.dbal.connections.default.configurationClass = "Doctrine\DBAL\Configuration";resources.doctrine.dbal.connections.default.sqlLoggerClass = "Doctrine\DBAL\Logging\EchoSQLLogger";resources.doctrine.dbal.connections.default.types.my_type = "Application\DBAL\Type\MyType"
; Database configuration;resources.doctrine.dbal.connections.default.parameters.wrapperClass = ""resources.doctrine.dbal.connections.default.parameters.driver = "pdo_mysql"resources.doctrine.dbal.connections.default.parameters.dbname = "fmm"resources.doctrine.dbal.connections.default.parameters.host = "localhost"resources.doctrine.dbal.connections.default.parameters.port = 3306resources.doctrine.dbal.connections.default.parameters.charset = "utf8"resources.doctrine.dbal.connections.default.parameters.user = "root"resources.doctrine.dbal.connections.default.parameters.password = "password";resources.doctrine.dbal.connections.default.parameters.driverOptions.ATTR_USE_BUFFERED_QUERIES = true
; ------------------------------------------------------------------------------; Doctrine ORM Configuration; ------------------------------------------------------------------------------
; Points to default EntityManager to be used. Optional if only one EntityManager is definedresources.doctrine.orm.defaultEntityManager = default
; EntityManager configuration for "default" manager;resources.doctrine.orm.entityManagers.default.id = default;resources.doctrine.orm.entityManagers.default.entityManagerClass = "Doctrine\ORM\EntityManager";resources.doctrine.orm.entityManagers.default.configurationClass = "Doctrine\ORM\Configuration";resources.doctrine.orm.entityManagers.default.entityNamespaces.app = "Application\Entity"resources.doctrine.orm.entityManagers.default.connection = defaultresources.doctrine.orm.entityManagers.default.proxy.autoGenerateClasses = falseresources.doctrine.orm.entityManagers.default.proxy.namespace = "Kdf\Entity\Proxy"resources.doctrine.orm.entityManagers.default.proxy.dir = APPLICATION_PATH "/models/Kdf/Entity/Proxy";resources.doctrine.orm.entityManagers.default.metadataCache = default;resources.doctrine.orm.entityManagers.default.queryCache = default;resources.doctrine.orm.entityManagers.default.resultCache = default;resources.doctrine.orm.entityManagers.default.DQLFunctions.numeric.PI = "DoctrineExtensions\ORM\Query\Functions\Numeric\PiFunction"resources.doctrine.orm.entityManagers.default.metadataDrivers.annotationRegistry.annotationFiles[] = APPLICATION_PATH "/../library/Doctrine/ORM/Mapping/Driver/DoctrineAnnotations.php";resources.doctrine.orm.entityManagers.default.metadataDrivers.annotationRegistry.annotationNamespaces.0.namespace = "Gedmo";resources.doctrine.orm.entityManagers.default.metadataDrivers.annotationRegistry.annotationNamespaces.0.includePath = APPLICATION_PATH "/../library/vendor"resources.doctrine.orm.entityManagers.default.metadataDrivers.drivers.0.adapterClass = "Doctrine\ORM\Mapping\Driver\AnnotationDriver"resources.doctrine.orm.entityManagers.default.metadataDrivers.drivers.0.mappingNamespace = "Kdf\Entity"resources.doctrine.orm.entityManagers.default.metadataDrivers.drivers.0.mappingDirs[] = APPLICATION_PATH "/models/Kdf/Entity"resources.doctrine.orm.entityManagers.default.metadataDrivers.drivers.0.annotationReaderClass = "Doctrine\Common\Annotations\AnnotationReader"resources.doctrine.orm.entityManagers.default.metadataDrivers.drivers.0.annotationReaderCache = default;resources.doctrine.orm.entityManagers.default.metadataDrivers.drivers.0.annotationReaderNamespaces.App = "Application\DoctrineExtensions\ORM\Mapping"
; ------------------------------; View and Lanout Configuration; ------------------------------
resources.layout.layout = "layout" resources.layout.layoutPath = APPLICATION_PATH "/layouts/scripts/"
resources.view.engines.php.class = "Ano_View_Engine_PhpEngine"resources.view.engines.php.viewSuffix = "phtml"
resources.view.engines.twig.class = "Ano_ZFTwig_View_Engine_TwigEngine"resources.view.engines.twig.isDefault = 1resources.view.engines.twig.viewSuffix = "twig" resources.view.engines.twig.options.charset = "utf-8"resources.view.engines.twig.options.strict_variables = 0resources.view.engines.twig.options.cache = APPLICATION_PATH "/../var/cache/twig"resources.view.engines.twig.options.auto_escape = 1resources.view.engines.twig.options.auto_reload = 1resources.view.engines.twig.options.debug = 0resources.view.engines.twig.options.trim_blocks = 1resources.view.engines.twig.extensions.helper.class = "Ano_ZFTwig_Extension_HelperExtension"resources.view.engines.twig.extensions.trans.class = "Ano_ZFTwig_Extension_TransExtension"
[staging : production]
[testing : production]phpSettings.display_startup_errors = 1phpSettings.display_errors = 1
[development : production]phpSettings.display_startup_errors = 1phpSettings.display_errors = 1resources.frontController.params.displayExceptions = 1
resources.doctrine.cache.instances.default.adapterClass = "Doctrine\Common\Cache\ArrayCache"resources.doctrine.orm.entityManagers.default.proxy.autoGenerateClasses = true
resources.doctrine.dbal.connections.default.parameters.host = "localhost"resources.doctrine.dbal.connections.default.parameters.dbname = "kdfdb"resources.doctrine.dbal.connections.default.parameters.user = "kdf"resources.doctrine.dbal.connections.default.parameters.password = "kdfpass"(その5へ続く)
Pingback: Zend Framework1 + Doctrine2 + twigを組み合わせる(その5) | KDF Memo