日頃の行い

個人的な日頃の行いをつらつら書いてます\\\\ ٩( 'ω' )و ////

PHPのLumenフレームワークでテンプレートエンジンとしてtwigを利用する

Laravel製のマイクロフレームワークLumenにちょっと触ってみました。
その時にテンプレートエンジンにTwigは使えないのかなぁと思ったので色々試してみた時の話です。

lumen.laravel.com

LumenではデフォルトのテンプレートとしてLaravelのBladeが利用されています。
個人的にいつもTwigをテンプレートエンジンとして利用していたので、Twigを使うにはどうすれば良いのかなぁと思って方法を探しました。
探してみたところTwigBridgeというものが見つかりました。
Lumenでの使い方も書かれていたので備忘録としてそのやり方を書いておこうかなと思います。

github.com

やること

  1. Lumenのインストール
  2. LumenのConfigを設定
  3. templateとrouting記述
  4. 動かしてみる

1. Lumenのインストール

こちらを参考にインストールしました。
http://lumen.laravel.com/docs/installation

ざっとやってみようと思います。
環境にはこちらのDockerコンテナ利用しました。
https://hub.docker.com/r/tarata/centos6-with-php56-node/

$curl -sS https://getcomposer.org/installer | php
#!/usr/bin/env php
All settings correct for using Composer
Downloading...

Composer successfully installed to: //composer.phar
Use it: php composer.phar
$php composer.phar global require "laravel/lumen-installer=~1.0"
Changed current directory to /root/.composer
./composer.json has been created
Loading composer repositories with package information
Updating dependencies (including require-dev)
  - Installing symfony/process (v2.7.3)
    Downloading: 100%

  - Installing symfony/console (v2.7.3)
    Downloading: 100%

  - Installing react/promise (v2.2.1)
    Downloading: 100%

  - Installing guzzlehttp/streams (3.0.0)
    Downloading: 100%

  - Installing guzzlehttp/ringphp (1.1.0)
    Downloading: 100%

  - Installing guzzlehttp/guzzle (5.3.0)
    Downloading: 100%

  - Installing laravel/lumen-installer (v1.0.1)
    Downloading: 100%

symfony/console suggests installing symfony/event-dispatcher ()
symfony/console suggests installing psr/log (For using the console logger)
Writing lock file
Generating autoload files
$env PATH=$PATH:$HOME/.composer/vendor/bin lumen new lumen-with-twig
Crafting application...
Application ready! Build something amazing.
$tree -L 2
.
└── lumen-with-twig
    ├── app
    ├── artisan
    ├── bootstrap
    ├── composer.json
    ├── composer.lock
    ├── database
    ├── phpunit.xml
    ├── public
    ├── readme.md
    ├── resources
    ├── server.php
    ├── storage
    ├── tests
    └── vendor
$cd lumen-with-twig
# composer.pharへのPATHは適当です
$php /path/to/composer.phar require rcrowe/twigbridge 0.8.x
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
  - Installing twig/twig (v1.21.1)
    Downloading: 100%

  - Installing rcrowe/twigbridge (v0.8.1)
    Downloading: 100%

rcrowe/twigbridge suggests installing twig/extensions (~1.0)
rcrowe/twigbridge suggests installing laravelcollective/html (For bringing back html/form in Laravel 5.x)
Writing lock file
Generating autoload files

これで準備完了。

2.LumenのConfigを設定

2つやることがあります。

  1. /bootstrap/app.phpに設定を追加。
  2. Configファイルの追加

70行目あたりのService Providersに追記。
/bootstrap/app.php

<?php
// ...省略

/*
|--------------------------------------------------------------------------
| Register Service Providers
|--------------------------------------------------------------------------
|
| Here we will register all of the application's service providers which
| are used to bind services into the container. Service providers are
| totally optional, so you are not required to uncomment this line.
|
*/

// $app->register(App\Providers\AppServiceProvider::class);
// $app->register(App\Providers\EventServiceProvider::class);

$app->configure('twigbridge'); //ここと
$app->register('TwigBridge\ServiceProvider'); //ここを追記

/vendor/rcrowe/twigbridge/config/twigbridge.phpをconfigディレクトリに追加します。
はじめから用意されてないので、作らないといけないとかちょっとハマりました。
Auth, Translator, Urlの拡張機能を無効化しないと使えないようなので、それを無効にする設定を書くための追加です。

$mkdir -p config
$cp vendor/rcrowe/twigbridge/config/twigbridge.php config/
$vi config/twigbridge.php

100行目あたりにExtensionが書いてあるのでそこの記述をコメントアウトします。

<?php
...省略

    'extensions' => [

        /*
        |--------------------------------------------------------------------------
        | Extensions
        |--------------------------------------------------------------------------
        |
        | Enabled extensions.
        |
        | `Twig_Extension_Debug` is enabled automatically if twig.debug is TRUE.
        |
        */
        'enabled' => [
            'TwigBridge\Extension\Loader\Facades',
            'TwigBridge\Extension\Loader\Filters',
            'TwigBridge\Extension\Loader\Functions',

//            'TwigBridge\Extension\Laravel\Auth', ここと
            'TwigBridge\Extension\Laravel\Config',
            'TwigBridge\Extension\Laravel\Dump',
            'TwigBridge\Extension\Laravel\Input',
            'TwigBridge\Extension\Laravel\Session',
            'TwigBridge\Extension\Laravel\String',
//            'TwigBridge\Extension\Laravel\Translator', ここと
//            'TwigBridge\Extension\Laravel\Url', ここ

            // 'TwigBridge\Extension\Laravel\Form',
            // 'TwigBridge\Extension\Laravel\Html',
            // 'TwigBridge\Extension\Laravel\Legacy\Facades',
        ],

これで設定も完了。

3. templateとrouting記述

lumenのテンプレートは/resources/viewsディレクトリに置くことになっているので、そちらにTwigのテンプレートを追加します。
bladeの場合、hogehoge.blade.phpのように拡張子phpですが、twigはいりません。
/resources/views/hello.twig

<h1>{{hello}}</h1>

そして、そのテンプレートを利用するように/app/Http/routes.phpへと追記します。

<?php

/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It is a breeze. Simply tell Lumen the URIs it should respond to
| and give it the Closure to call when that URI is requested.
|
*/

$app->get('/', function () use ($app) {
    return $app->welcome();
});

//ここを追記
$app->get('/hello', function () use ($app) {
    return view('hello', ['hello' => 'world']);
});

これで動くはず。

4.動かしてみる

画面で写すほどのものでもないので、curlを叩きました。

$php artisan serve &
Lumen development server started on http://localhost:8000/
$curl localhost:8000/hello
<h1>world</h1>

動いた。
でもまあ最近bladeを使っている限りそんなに大変でもなかったので、bladeでもいいんじゃないかなって思いました。
bladeとtwigどんな違いがあるのかなぁ。