Using $this when not in object context when reading cookies
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.
Solution 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
- Cookbook > Controllers > Components > Accessing a Component's Controller
- Cookbook > Request & Response Objects > Cookies