PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, December 30, 2021

[FIXED] Session object not available from Component

 December 30, 2021     cakephp, cakephp-3.0, php     No comments   

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
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing