【问题标题】:Session object not available from Component组件不提供会话对象
【发布时间】:2021-08-19 13:48:03
【问题描述】:

我收到以下错误:

Call to undefined method App\Controller\Component\MyCustomComponent::getRequest()

根据有关使用Sessions 的文档,我应该可以从Components 调用getRequest()https://book.cakephp.org/3/en/development/sessions.html

代码

class SomethingController extends AppController
{

    public function initialize()
    {
        parent::initialize();
        $this->loadComponent('MyCustom');
    }
    public function view($id = null)
    {
        $this->MyCustom->someMethodHere();
    }
}

class MyCustomComponent extends Component
{

    function __construct() {
        $this->otherClass = new OtherClass();
    }
    ...
    // Prior to 3.6.0 use session() instead.
    $name = $this->getRequest()->getSession()->read('myKey');

}

纠正此错误的最佳方法是什么? IIRC,这可能是因为我错过了对父构造函数的调用? IE。 parent::__contruct()

class MyCustomComponent extends Component
{

    function __construct() {
        //parent::__construct(); intellisence indicates I'm missing parameters
        $this->otherClass = new OtherClass();
    }
    ...
    // Prior to 3.6.0 use session() instead.
    $name = $this->getRequest()->getSession()->read('myKey');

}

编辑#1

父构造函数看起来像这样:

public function __construct(ComponentRegistry $registry, array $config = []) { }

我这样修改了我的代码,但错误仍然存​​在:

...
use Cake\Controller\ComponentRegistry;

...

function __construct(ComponentRegistry $registry, array $config = []) {
    parent::__construct($registry, $config);
    $this->otherClass = new OtherClass();
}

编辑#2

我尝试了initialize 方法而不是__construct 方法,但是得到了相同的结果:

function initialize(array $config)
{
    parent::initialize($config);
    $this->otherClass = new OtherClass();
}

【问题讨论】:

    标签: php cakephp cakephp-3.0


    【解决方案1】:

    getRequest() 是控制器的方法,而不是组件。您需要添加getController 调用:

    $name = $this->getController()->getRequest()->getSession()->read('myKey');
    

    【讨论】:

      【解决方案2】:

      您不必必须调用父构造函数,但您通常希望这样做,以便获得它所做的任何配置。检查父构造函数的代码,看看它需要什么参数,配置你的参数,然后传递它们。例如,如果父母看起来像这样:

      function __construct(Foo $foo) {
          ...
      }
      

      那么你想在你的课堂上做这样的事情:

      function __construct(Foo $foo) {
          parent::__construct($foo);
          $this->otherClass = new OtherClass();
      }
      

      【讨论】:

      • 我的印象是我的错误是由于没有调用父构造函数导致 getRequest() 方法不可用?
      • 当然可以,如果父构造函数设置请求对象。
      • 查看编辑#1 和更新的构造函数。不幸的是,错误仍然存​​在。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-19
      • 2011-01-22
      相关资源
      最近更新 更多