LoginSignup
19
17

More than 5 years have passed since last update.

CakePHP 3.0 新機能Cellを試してみた

Last updated at Posted at 2014-09-10

CakePHP 3.0 新機能Cellを試してみた

前提条件

  • CakePHP 3.0(beta1)を利用(2014/09/10)

Cellとは

・Controller付きのElementのようなもの?

 既存のCakePHPだとホームページのサイドバーに新着情報を表示しようと思うとAppControllerのbeforeFiltter辺りにロジックを追加して毎回実行できる状態にするかrequestActionを使う必要があった。

 ※CellはCakePHP2系までのrequestActionの強化版みたいなもの
 

準備

・Cellの作成はbakeから行うことが出来る。

// HogeがCell名
php bin/cake.php bake cell Hoge

コマンドを実行することで以下の3ファイルが作成される

・src/Template/Cell/Hoge/display.ctp // Viewファイル

・src/View/Cell/HogeCell.php // CellのControllerのようなもの

・Test/TestCase/View/Cell/HogeCellTest.php // テスト

使い方

・elementと同じような使い方である。
 適当なViewファイルでcellを実行するだけ。

<?= $this->cell("Hoge"); ?>

※これを実行するとHogeCell.phpdisplayメソッドが実行されてdisplay.ctpがレンダリングされる

その他

・Cellの中に複数のアクションを作ることが出来る

// アクションを追加
class HogeCell extends Cell {
    function display() {
        // デフォルトのアクション
    }

    function display2() {
        // 追加アクション
    }
}

// ctpからの実行
<?= $this->cell("Hoge::display2"); ?>

・Controllerからも実行することが出来る

use Cake\View\CellTrait;  // 追加
class UsersController extends AppController {
  use CellTrait; // 追加

  function index() {
    // cellの実行(動作はViewで実行した場合と同じ)
    echo $this->cell('Hoge');
  }
}
19
17
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
19
17