LoginSignup
2
2

More than 5 years have passed since last update.

CakePHP3新機能 View Cell の利用手順

Last updated at Posted at 2016-12-20

公式ドキュメント

http://book.cakephp.org/3.0/ja/views/cells.html

利用手順

1. bakeを実行

プロジェクトルートで以下のコマンドを実行すると、必要なファイルが生成されます。

bin/cake bake cell hoge

テストコードも生成してくれるので、きちんと活用していきましょう。

[root@vagrant-centos65 test-project]# bin/cake bake cell hoge
Welcome to CakePHP v3.3.6 Console
---------------------------------------------------------------
App : src
Path: /var/www/test-project/src/
PHP : 7.0.11
---------------------------------------------------------------

Creating file /var/www/test-project/src/Template/Cell/Hoge/display.ctp
Wrote `/var/www/test-project/src/Template/Cell/Hoge/display.ctp`

Creating file /var/www/test-project/src/View/Cell/HogeCell.php
Wrote `/var/www/test-project/src/View/Cell/HogeCell.php`

Baking test case for App\View\Cell\HogeCell ...

Creating file /var/www/test-project/tests/TestCase/View/Cell/HogeCellTest.php
Wrote `/var/www/test-project/tests/TestCase/View/Cell/HogeCellTest.php`

2. TemplateにCellの呼び出しコードを配置

TemplateにCellを配置しましょう。
あとは表示したい内容に合わせて編集していくだけです。

Template/Pages/home.ctp
<?= $this->cell('Hoge')->render() ?>

3. View\Cellの編集

View\Cell以下に以下のようなクラスが生成されているので、Controllerと同じ感覚で編集します。
$_validCellOptionsについては、補足資料を参照してください。

Cellを呼び出す際はdisplayメソッドが呼び出されます。
公式ドキュメントにはdisplayメソッド以外を呼び出す方法も記述されていますが、
ただでさえMVCからMVCを呼ぶという複雑なことをしているので、避けたほうが無難でしょう。

<?php
namespace App\View\Cell;

use Cake\View\Cell;

/**
 * Hoge cell
 */
class HogeCell extends Cell
{

    /**
     * List of valid options that can be passed into this
     * cell's constructor.
     *
     * @var array
     */
    protected $_validCellOptions = [];

    /**
     * Default display method.
     *
     * @return void
     */
    public function display()
    {
        // loadModelも使える
        $hoge_entity= $this->loadModel('Hoges')->get(1);

        // controller同様、setメソッドで登録する
        $this->set('hoge_entity', $hoge_entity);
    }
}

4. Template\Cellの編集

bakeを叩いた直後の状態では、Template\Cellにdisplay.ctpが格納されています。
こちらを通常のTemplateと同様に編集していきます。

Template\Cell\display.ctp
<div><?= $hoge_entity->id ?></div>
result
<div>1</div>

補足資料. Cellメソッドの詳細

http://qiita.com/morisuke/items/c7b8fda6588108a55f3f

2
2
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
2
2