【发布时间】: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