Issue
I get the following error:
Call to undefined method App\Controller\Component\MyCustomComponent::getRequest()
Per the documentation on using Sessions
, I should be able to call getRequest()
from Components
:
https://book.cakephp.org/3/en/development/sessions.html
Code
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');
}
What's the best way to remedy this error? IIRC, it may be due to the fact that I'm missing a call to the parent constuctor? 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');
}
Edit #1
The parent constructor seems to look like this:
public function __construct(ComponentRegistry $registry, array $config = []) { }
I modified my code like this, but the error remains:
...
use Cake\Controller\ComponentRegistry;
...
function __construct(ComponentRegistry $registry, array $config = []) {
parent::__construct($registry, $config);
$this->otherClass = new OtherClass();
}
Edit #2
I tried the initialize
method instead of the __construct
method, however, getting the same results:
function initialize(array $config)
{
parent::initialize($config);
$this->otherClass = new OtherClass();
}
Solution
getRequest()
is a method of controllers, not components. What you need is to add the getController
call:
$name = $this->getController()->getRequest()->getSession()->read('myKey');
Answered By - Greg Schmidt
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.