getRequest in component cakeph 3.8

Hello

I’ve upgraded from 3.4 to 3.8 - yeah I know it’s a little late :slight_smile:

I have a component which is handling setting session variables amongst other things. Previously it have lines like:

$this->request->session()->write(‘Config.settingId’, $settings_array->id);

After the upgrade to 3.8 this is failing - due to I believe $this->reesut becoming $this->getRequest

So i’ve changed it to:

$session = $this->getRequest()->getSession();
$session->write(‘Config.settingId’, $settings_array->id);

As in the documentation however it then fail with;

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

Any Ideas please and how I resolve this?

The request is still on the controller so

//$this is your Component
$this->getController()->getRequest()->getSession();

Hello
I’m facing the same issue in cake 3.8 componet using this overcome from that issue, but now get

Call to a member function getController() on null
how to fix this?

Already add

use Cake\Controller\Controller;

still getting error

So, $this is null in your component? Is it a static function in the component? Otherwise, that should never be the case.

So, you are making a call like this:

$something->getController();

The message is telling you that $something is NULL.

Look at your code again. It sounds like a simple typo or use of the wrong variable.

If this code is in a component, $this holds the component and $this->getController() would be the expected call.

namespace App\Controller\Component;

use Cake\Controller\Component;
use Cake\Mailer\Email;
use Cake\Filesystem\Folder;
use Cake\Filesystem\File;
use Cake\Controller\Controller;

class CustomComponent extends Component {

    function __construct($prompt = null) {
        
    }

    function uploadImageBanner($tmp_name, $name, $path, $imgWidth) {
            $user_id = $this->getController()->getRequest()->getSession()->read('Auth.User.id'); **// get error here**
          //code here
        //
    }



}

This is my component code
Can you check what is the issue.

$this->request->getSession(); that should work

maybe the problem is that Auth.User.id not set in the session?

Auth.User.id already set in controller when user logged in.

$this->request->getSession(); is for cake 3.5 or lower
I’m using cake 3.8.

in cake3.8
$this->request->getSession(); //shows deprecated notice

You’ve overridden the default component constructor with your own, but not called the parent one.

1 Like

Can you explain it bit more? I’m still not get how to call parent one any example

It’s not something specific to components. In general, in PHP, when you create a class that extends another class, and you have a __construct function, your function should take all the same parameters as the parent’s __construct function does, and then you do parent::__construct(...) with all the parameters in the … spot.