フルスタックかつ軽量!CodeIgniterを試す-View編

こんにちは、コバヤシです。
前回に引き続き、CodeIgniterを試していきます。今回はViewの設定を行います。

tech.arms-soft.co.jp

View

CodeIgniterのviewのレンダーは標準では、素のPHPで行われます。

<?php

namespace App\Controllers;

class Home extends BaseController
{
    public function index()
    { 
        return view('hoge', ['foo' => 'デモです']);
    }
}
<body>

<p>テスト</p>

<p>
<?= $foo ?>
</p>
</body>

HTML上にPHPを記述するのと同じですね。
これはこれで問題はないのですが、実際に使っていく中では不便なところが出てくると思います。
そこでテンプレートエンジンを導入していきます。

テンプレートエンジンにBladeを使う

CodeIgniterのテンプレートエンジンで検索すると「Twig」を使う例が出てきます。便利なComposerのライブラリもあるようです。
しかし、今までLaravelでBladeを使ってきた身からするとCodeIgniterでもBladeを使ってみたい。。
そこでCodeIgniterでBladeを使えるようにしてみたいと思います。

BladeはLaravelで使用しているものをそのまま使用できないので「BladeOne」を使用します。

github.com

まずはComposerでBladeOneをインストールします。

composer require eftec/bladeone

次に、サービスに登録します。

cahceディレクトリにはwritable/blade/cacheを指定します。 ディレクトリは作成しなくても勝手に作られます。

codeigniter/app/Config/Services.php

<?php

namespace Config;

use CodeIgniter\Config\BaseService;
use eftec\bladeone\BladeOne; // 追加

class Services extends BaseService
{
    /*
     * public static function example($getShared = true)
     * {
     *     if ($getShared) {
     *         return static::getSharedInstance('example');
     *     }
     *
     *     return new \CodeIgniter\Example();
     * }
     */
    
    // 追加
    public static function blade($getShared = true)
    {
        if ($getShared) {
            return static::getSharedInstance('blade');
        }

        $views = APPPATH . 'Views';
        $cache = WRITEPATH . 'blade' . DIRECTORY_SEPARATOR . 'cache';
        
        return new BladeOne($views, $cache, BladeOne::MODE_DEBUG);
    }
}

レンダーするためのメソッドを追加します。

app/Common.php

<?php

/**
 * The goal of this file is to allow developers a location
 * where they can overwrite core procedural functions and
 * replace them with their own. This file is loaded during
 * the bootstrap process and is called during the frameworks
 * execution.
 *
 * This can be looked at as a `master helper` file that is
 * loaded early on, and may also contain additional functions
 * that you'd like to use throughout your entire application
 *
 * @see: https://codeigniter4.github.io/CodeIgniter4/
 */

use \Config\Services; // 追加

// 以下を追加
function bladeView($name, $data = [])
{
    $blade = Services::blade();

    return $blade->run($name, $data);
}

準備が出来たので、Bladeを使っていきます。

コントローラーで
return viewとしていたところをreturn bladeViewに変えます。

<?php

namespace App\Controllers;

class Home extends BaseController
{
    public function index()
    {
        return bladeView('hoge', ['foo' => 'デモです']);
    }
}

viewファイルは通常のBladeと同じく、ファイル名をxxxxx.blade.phpとして作成します。 使い方も同じです。

<body>

<p>
    {{ $foo }}
</p>
</body>

これでアクセスすれば「デモです」と表示されます。

まとめ

CodeIgniterでは色々と準備されていることもあり、比較的簡単にBladeと連携することが出来ました。
この調子で次回はDBまわりをやってみたいと思います。