-1

I'm attempting to read cookies inside a Component and getting an error in the Cookie class?

Using $this when not in object context
CORE\src\Http\Cookie\Cookie.php:738

[![enter image description here][1]][1]

Code:

<?php
namespace WetKit\Controller\Component;

use Cake\Controller\Component;
use Cake\Controller\Component\AuthComponent;
use Cake\Core\Configure;
use Cake\I18n\I18n;
use Cake\I18n\Time;
use Cake\ORM\Entity;
use Cake\Utility\Text;
use Cake\Http\Cookie\Cookie;
use Cake\Http\Cookie\CookieCollection;

class WetKitComponent extends Component
{
    public function init($configs = [])
    {
        ...
        debug(Cookie::read("wetkit.lang"));
        ...
    }
    ...
}

Edit 2

With the following code:

$cookieInstance = new Cookie('test'); 
debug($cookieInstance->read("wetkit.lang"));

I get:

Invalid data type, must be an array or \ArrayAccess instance.
InvalidArgumentException
Toggle Vendor Stack Frames
CORE\src\Utility\Hash.php:52

Edit 3

If I pass the request to my component like so:

//Setting core values for project
$this->appData = $this->WetKit->init([
    'request' => $this->request,
    ...
]);

Then, in my component:

debug($configs['request']->getCookie('wetkit.lang'));

I no longer get an error and it will output null. Unsure if this is a valid approach.

TechFanDan
  • 3,329
  • 6
  • 46
  • 89
  • 1
    That's because you do not have an actual instance of your Cookie class here, but you are calling the method statically with `Cookie::read`. Since there is no object instance, there is no `$this` available either. – CBroe Jan 21 '22 at 11:53
  • `$cookieInstance = new Cookie(); debug($cookieInstance->read("wetkit.lang"));` should work. – CBroe Jan 21 '22 at 11:55
  • Unfortunately, doesn't work. Even when I specify the string parameter to cookie, it fails somewhere else. Maybe I should pass the request up to my component somehow and get it that way? – TechFanDan Jan 21 '22 at 12:06

1 Answers1

1

The incorrect code usage aside, components can access the controllers they are attached to, and from there you can obtain the request object, from which you can then read cookies.

$this->getController()->getRequest()->getCookie('wetkit.lang')

See also

ndm
  • 59,784
  • 9
  • 71
  • 110