【问题标题】:CakePHP 3 - How to load componentsCakePHP 3 - 如何加载组件
【发布时间】:2016-08-07 14:44:20
【问题描述】:

在 CakePHP 2 中,您可以通过提供 $components 属性来指定要在控制器中加载哪些组件。

class AppController extends Controller
{

    public $components = [
        'RequestHandler',
        'Security'
    ];
}

我注意到这在 CakePHP 3 中仍然有效,但本书的大部分内容都使用了一种新方法,您可以分别加载每个组件:

public function initialize()
{
    $this->loadComponent('RequestHandler');
    $this->loadComponent('Security');
}

$components 属性是否仅用于向后兼容?我想用正确的 Cake 3 方法来做,特别是如果前一种方法将来会被弃用。


这两种方法的功能有什么不同吗?

如果我尝试像这样配置 SecurityComponent,它不起作用,并且配置似乎被完全忽略,即使它是该方法的有效使用:

public function initialize()
{
    $this->loadComponent('Security', ['blackHoleCallback', 'blackhole']);
}

相反,我必须在 beforeFilter() 中进行单独的方法调用来设置配置并使其实际工作:

public function initialize()
{
    $this->loadComponent('Security');
}

public function beforeFilter(Event $event)
{
    $this->Security->config('blackHoleCallback', 'blackhole');
}

但是,旧的“蛋糕 2”方式仍然可以正常工作:

class AppController extends Controller
{

    public $components = [
        'RequestHandler',
        'Security' => ['blackHoleCallback' => 'blackhole']
    ];
}

【问题讨论】:

    标签: cakephp cakephp-3.0


    【解决方案1】:

    是否提供 $components 属性只是为了向后兼容?我想用正确的 Cake 3 方法来做,特别是如果前一种方法将来会被弃用。

    它还没有被弃用as you can see here。但是通过方法调用加载它是更好的方法。我猜该属性将在 4.x 中被删除,并且可能在未来的 3.x 版本中被弃用。

    也请阅读以下内容:

    【讨论】:

      猜你喜欢
      • 2016-12-08
      • 2015-09-30
      • 2013-06-22
      • 2015-06-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-20
      • 2018-02-11
      相关资源
      最近更新 更多