In CakePHP 2 you could specify which components to load in the controller by providing a $components
property.
class AppController extends Controller
{
public $components = [
'RequestHandler',
'Security'
];
}
I notice this still works in CakePHP 3 but that most of the book uses a new method in which you load every component separately:
public function initialize()
{
$this->loadComponent('RequestHandler');
$this->loadComponent('Security');
}
Is the $components
property provided only for backwards compatibility? I want to do it the correct Cake 3 way, especially if the former method will be deprecated at some point in the future.
Are there any differences in functionality between the two methods?
If I try to configure the SecurityComponent like this, it doesn't work and the configuration seems to be completely ignored, even though it's a valid use of the method:
public function initialize()
{
$this->loadComponent('Security', ['blackHoleCallback', 'blackhole']);
}
Instead, I have to make a separate method call in beforeFilter()
to set the configuration and get it to actually work:
public function initialize()
{
$this->loadComponent('Security');
}
public function beforeFilter(Event $event)
{
$this->Security->config('blackHoleCallback', 'blackhole');
}
However, the old 'Cake 2' way still works fine:
class AppController extends Controller
{
public $components = [
'RequestHandler',
'Security' => ['blackHoleCallback' => 'blackhole']
];
}
答案 0 :(得分:1)
$ components属性是否仅提供向后兼容性?我想用正确的Cake 3方式做到这一点,特别是如果以前的方法将在某个时候被弃用。
尚未弃用as you can see here。但是通过方法调用加载它是更好的方法。我想该属性将在4.x中被删除,并且可能在将来的3.x版本中被弃用。
阅读这些内容: