ビューセル
多くのアプリケーションでは、ページ間、またはページ上の異なる場所で繰り返し使用できる小さなビュー断片があります。これらは、ヘルプボックス、ナビゲーションコントロール、広告、ログインフォームなどです。CodeIgniterでは、これらのプレゼンテーションブロックのロジックをビューセル内にカプセル化できます。基本的に、他のビューに含めることができるミニビューです。セル固有の表示ロジックを処理するためのロジックを組み込むことができます。各セルのロジックを独自のクラスに分離することで、ビューの可読性と保守性を向上させるために使用できます。
シンプルセルと制御セル
CodeIgniterは、シンプルセルと制御セルの2種類のビューセルをサポートしています。
**シンプルビューセル**は、任意のクラスとメソッドから生成でき、文字列を返すことを除いて、特別なルールに従う必要はありません。
**制御ビューセル**は、Codeigniter\View\Cells\Cell
クラスを継承するクラスから生成する必要があります。これにより、ビューセルの柔軟性と使用速度が向上します。
ビューセルの呼び出し
使用するビューセルの種類に関係なく、view_cell()
ヘルパー関数を使用して、任意のビューから呼び出すことができます。
最初のパラメーターは、(1)呼び出すクラスとメソッドの名前(シンプルセル)、または(2)呼び出すクラスとオプションのメソッドの名前(制御セル)です。2番目のパラメーターは、メソッドに渡すパラメーターの配列または文字列です。
// In a View.
// Simple Cell
<?= view_cell('App\Cells\MyClass::myMethod', ['param1' => 'value1', 'param2' => 'value2']) ?>
// Controlled Cell
<?= view_cell('App\Cells\MyCell', ['param1' => 'value1', 'param2' => 'value2']) ?>
セルが返す文字列は、view_cell()
関数が呼び出されたビューに挿入されます。
名前空間の省略
バージョン4.3.0の新機能。
クラスの完全な名前空間を含めない場合、App\Cells
名前空間にあると想定されます。したがって、次の例では、**app/Cells/MyClass.php**にあるMyClass
クラスを検索しようとします。そこにない場合、すべての名前空間がスキャンされ、各名前空間の**Cells**サブディレクトリ内で検索されます。
// In a View.
<?= view_cell('MyClass::myMethod', ['param1' => 'value1', 'param2' => 'value2']) ?>
キー/値文字列としてのパラメーターの受け渡し
パラメーターは、キー/値文字列として渡すこともできます。
// In a View.
<?= view_cell('MyClass::myMethod', 'param1=value1, param2=value2') ?>
シンプルセル
シンプルセルは、選択したメソッドから文字列を返すクラスです。シンプルな警告メッセージセルの例を以下に示します。
<?php
namespace App\Cells;
class AlertMessage
{
public function show(array $params): string
{
return "<div class=\"alert alert-{$params['type']}\">{$params['message']}</div>";
}
}
ビュー内では次のように呼び出します。
// In a View.
<?= view_cell('AlertMessage::show', ['type' => 'success', 'message' => 'The user has been updated.']) ?>
さらに、メソッドのパラメーター変数と一致するパラメーター名を使用して、可読性を向上させることができます。このように使用する場合、ビューセルの呼び出しではすべてのパラメーターを常に指定する必要があります。
// In a View.
<?= view_cell('Blog::recentPosts', 'category=codeigniter, limit=5') ?>
<?php
// In a Cell.
namespace App\Cells;
class Blog
{
// ...
public function recentPosts(string $category, int $limit): string
{
$posts = $this->blogModel->where('category', $category)
->orderBy('published_on', 'desc')
->limit($limit)
->get();
return view('recentPosts', ['posts' => $posts]);
}
}
制御セル
バージョン4.3.0の新機能。
制御セルには、(1)セルの構築をできるだけ高速化すること、(2)必要に応じてビューに追加のロジックと柔軟性を提供すること、という2つの主な目標があります。
クラスはCodeIgniter\View\Cells\Cell
を継承する必要があります。同じフォルダーにビューファイルが必要です。慣例により、クラス名はPascalCaseでCell
をサフィックスとして付け、ビューはクラス名のsnake_caseバージョンで、サフィックスなしになります。たとえば、MyCell
クラスがある場合、ビューファイルはmy.php
になります。
注記
v4.3.5より前は、生成されたビューファイルは_cell.php
で終わっていました。v4.3.5以降は_cell
サフィックスなしでビューファイルが生成されますが、既存のビューファイルは引き続き検索およびロードされます。
制御セルの作成
最も基本的なレベルでは、クラス内に実装する必要があるのはパブリックプロパティだけです。これらのプロパティは、ビューファイルで自動的に使用できるようになります。
上記のAlertMessageを制御セルとして実装すると、次のようになります。
<?php
// app/Cells/AlertMessageCell.php
namespace App\Cells;
use CodeIgniter\View\Cells\Cell;
class AlertMessageCell extends Cell
{
public $type;
public $message;
}
// app/Cells/alert_message.php
<div class="alert alert-<?= esc($type, 'attr') ?>">
<?= esc($message) ?>
</div>
// Called in main View:
<?= view_cell('AlertMessageCell', 'type=warning, message=Failed.') ?>
コマンドによるセルの生成
CLIから組み込みコマンドを使用して、制御セルを作成することもできます。コマンドはphp spark make:cell
です。1つの引数、つまり作成するセルの名前を取ります。名前はPascalCaseにする必要があり、クラスは**app/Cells**ディレクトリに作成されます。ビューファイルも**app/Cells**ディレクトリに作成されます。
php spark make:cell AlertMessageCell
異なるビューの使用
クラスのview
プロパティを設定して、カスタムビュー名を指定できます。ビューは、通常のビューと同様に配置されます。
<?php
namespace App\Cells;
use CodeIgniter\View\Cells\Cell;
class AlertMessageCell extends Cell
{
public $type;
public $message;
protected string $view = 'my/custom/view';
}
レンダリングのカスタマイズ
HTMLのレンダリングをより詳細に制御する必要がある場合は、render()
メソッドを実装できます。このメソッドを使用すると、追加のロジックを実行し、必要に応じてビューに追加のデータを渡すことができます。render()
メソッドは文字列を返す必要があります。
制御セルの全機能を利用するには、通常のview()
ヘルパー関数の代わりに$this->view()
を使用する必要があります。
<?php
namespace App\Cells;
use CodeIgniter\View\Cells\Cell;
class AlertMessageCell extends Cell
{
public $type;
public $message;
public function render(): string
{
return $this->view('my/custom/view', ['extra' => 'data']);
}
}
計算プロパティ
1つ以上のプロパティに対して追加のロジックを実行する必要がある場合は、計算プロパティを使用できます。これには、プロパティをprotected
またはprivate
に設定し、プロパティ名をget
とProperty
で囲んだ名前のパブリックメソッドを実装する必要があります。
// In a View. Initialize the protected properties.
<?= view_cell('AlertMessageCell', ['type' => 'note', 'message' => 'test']) ?>
<?php
// app/Cells/AlertMessageCell.php
namespace App\Cells;
use CodeIgniter\View\Cells\Cell;
class AlertMessageCell extends Cell
{
protected $type;
protected $message;
private $computed;
public function mount(): void
{
$this->computed = sprintf('%s - %s', $this->type, $this->message);
}
public function getComputedProperty(): string
{
return $this->computed;
}
public function getTypeProperty(): string
{
return $this->type;
}
public function getMessageProperty(): string
{
return $this->message;
}
}
// app/Cells/alert_message.php
<div>
<p>type - <?= esc($type) ?></p>
<p>message - <?= esc($message) ?></p>
<p>computed: <?= esc($computed) ?></p>
</div>
重要
セル初期化中にprivateとして宣言されたプロパティを設定することはできません。
プレゼンテーションメソッド
ビューに対して追加のロジックを実行する必要がある場合がありますが、パラメーターとして渡したくない場合があります。セルビュー自体から呼び出されるメソッドを実装できます。これにより、ビューの可読性が向上します。
<?php
// app/Cells/RecentPostsCell.php
namespace App\Cells;
use CodeIgniter\View\Cells\Cell;
class RecentPostsCell extends Cell
{
protected $posts;
public function linkPost($post): string
{
return anchor('posts/' . $post->id, $post->title);
}
}
// app/Cells/recent_posts.php
<ul>
<?php foreach ($posts as $post): ?>
<li><?= $this->linkPost($post) ?></li>
<?php endforeach ?>
</ul>
セットアップロジックの実行
ビューがレンダリングされる前に追加のロジックを実行する必要がある場合は、mount()
メソッドを実装できます。このメソッドは、クラスのインスタンス化直後に呼び出され、追加のプロパティの設定やその他のロジックの実行に使用できます。
<?php
namespace App\Cells;
use CodeIgniter\View\Cells\Cell;
class RecentPostsCell extends Cell
{
protected $posts;
public function mount(): void
{
$this->posts = model('PostModel')->orderBy('created_at', 'DESC')->findAll(10);
}
}
view_cell()
ヘルパー関数に配列として追加パラメータを渡すことで、mount()
メソッドに追加パラメータを渡すことができます。mount()
メソッドのパラメータ名と一致するパラメータは、すべて渡されます。
<?php
// app/Cells/RecentPostsCell.php
namespace App\Cells;
use CodeIgniter\View\Cells\Cell;
class RecentPostsCell extends Cell
{
protected $posts;
public function mount(?int $categoryId): void
{
$this->posts = model('PostModel')
->when(
$categoryId,
static fn ($query, $categoryId) => $query->where('category_id', $categoryId)
)
->orderBy('created_at', 'DESC')
->findAll(10);
}
}
// Called in main View:
<?= view_cell('RecentPostsCell', ['categoryId' => 5]) ?>
セルキャッシュ
3番目のパラメータとして、データをキャッシュする秒数を指定することで、ビューセルの呼び出し結果をキャッシュできます。これは、現在設定されているキャッシュエンジンを使用します。
// Cache the view for 5 minutes
<?= view_cell('App\Cells\Blog::recentPosts', 'limit=5', 300) ?>
必要に応じて、自動生成された名前の代わりにカスタム名を使用できます。新しい名前を4番目のパラメータとして渡してください。
// Cache the view for 5 minutes
<?= view_cell('App\Cells\Blog::recentPosts', 'limit=5', 300, 'newcacheid') ?>