2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

CakePHP3 コンポーネント、ヘルパーまとめ

2
Last updated at Posted at 2017-12-16

問題

以下のような書き方は、もう deprecated

Controller/HogeController.php
class HogeController extends AppController
{
    public $components = [
        'Foo',
        'Bar',
    ];

    public $helpers = [
        'Form',
        'Html',
    ];

https://api.cakephp.org/3.5/class-Cake.Controller.Controller.html#$components
https://api.cakephp.org/3.5/class-Cake.Controller.Controller.html#$helpers

対応

コンポーネント

You should configure components in your Controller::initialize() method.

Controller/HogeController.php
class HogeController extends AppController
{
    public function initialize()
    {
        parent::initialize();

        $this->loadComponent('Foo');
        $this->loadComponent('Bar', [
            'some' => 'option',
        ]);
    }

ヘルパー

You should configure helpers in your AppView::initialize() method.

View/AppView.php
class AppView extends View
{
    public function initialize()
    {
        parent::initialize();

        $this->loadHelper('Foo');
        $this->loadHelper('Bar', [
            'ore' => 'motion',
        ]);
    }

または

Controller/HogeController.php
class HogeController extends AppController
{
    public function beforeRender(Event $event)
    {
        parent::beforeRender($event);

        $this->viewBuilder()->helpers(['Foo']);
    }

CakePHP やアプリケーションにあるヘルパーを明示的に読み込む必要はありません。 これらのヘルパーは、初回の使用時に遅延ロードされます。
https://book.cakephp.org/3.0/ja/views/helpers.html#configuring-helpers

ビヘイビア

Model/Table/HogeTable.php
class HogeTable extends Table
{
    public function initialize(array $config)
    {
        $this->addBehavior('Baz');
    }
}

モデルとか

Controller/HogeController.php
class HogeController extends AppController
{
    public function initialize()
    {
        parent::initialize();

        $this->loadModel('Foo');
    }

    public function index()
    {
        $foos = $this->Foo->find()->all();
        $this->set(compact('foos'));
    }

とか

Controller/HogeController.php
class HogeController extends AppController
{
    public function index()
    {
        $foos = TableRegistry::get('Foo')->find()->all();
        $this->set(compact('foos'));
    }

コントローラ上での使い分け

コントローラ上でのController::loadModel()TableRegistry::get()の使い分け

  • 気分
  • コントローラ全体で使う場合はController::loadModel() 
  • その場しのぎはTableRegistry::get()
  • ごにょごにょしたい場合はTableRegistry::get()

環境

  • CakePHP: 3.5.7
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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?