0

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']
    ];
}
BadHorsie
  • 14,135
  • 30
  • 117
  • 191

1 Answers1

1

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.

It's not yet deprecated as you can see here. But loading it via the method call is the better way of doing it. I guess the property is going to be dropped in 4.x and maybe deprecated in in a future version of 3.x.

Read these as well:

Community
  • 1
  • 1
floriank
  • 25,546
  • 9
  • 42
  • 66