問題
以下のような書き方は、もう deprecated
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.
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.
class AppView extends View
{
public function initialize()
{
parent::initialize();
$this->loadHelper('Foo');
$this->loadHelper('Bar', [
'ore' => 'motion',
]);
}
または
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
ビヘイビア
class HogeTable extends Table
{
public function initialize(array $config)
{
$this->addBehavior('Baz');
}
}
モデルとか
class HogeController extends AppController
{
public function initialize()
{
parent::initialize();
$this->loadModel('Foo');
}
public function index()
{
$foos = $this->Foo->find()->all();
$this->set(compact('foos'));
}
とか
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