TechFanDan
TechFanDan

Reputation: 3482

Session object not available from Component

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();
}

Upvotes: 0

Views: 194

Answers (2)

Greg Schmidt
Greg Schmidt

Reputation: 5099

getRequest() is a method of controllers, not components. What you need is to add the getController call:

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

Upvotes: 3

Alex Howansky
Alex Howansky

Reputation: 53533

You don't have to call the parent constructor, but you usually want to, so that you get whatever configuration it does. Inspect the code for the parent constructor, see what parameters it takes, configure yours to take the same, then pass them through. For example, if the parent looks like this:

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

Then you want to do something like this in your class:

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

Upvotes: 1

Related Questions