cakephp 阅读Cookie时,如果不在对象上下文中,则使用$this

j2cgzkjk  于 2022-11-11  发布在  PHP
关注(0)|答案(1)|浏览(141)

我试图读取Component内的cookie,但在Cookie类中出现错误?

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

[![在此处输入图像说明][1]][1]
编码:

<?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"));
        ...
    }
    ...
}

编辑2

使用以下代码:

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

我得到:

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

编辑3

如果将请求传递给组件,如下所示:

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

然后,在我的组件中:

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

我不再得到一个错误,它将输出null。不确定这是否是一个有效的方法。

6mw9ycah

6mw9ycah1#

除了不正确的代码用法之外,组件可以访问它们所连接到的控制器,并从那里获得请求对象,然后从该对象读取cookie。

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

另请参阅

*Cookbook〉控制器〉组件〉访问组件的控制器
*Cookbook〉请求和响应对象〉Cookie

相关问题