Yii2 -如何访问配置config/web.php中的cookie



我想在我的Yii2基本项目中使用botstrap操作创建一个亮/暗切换,我的伪代码是这样的

在动作所有控制器之前,我检查动作请求是否有cookie主题

'on beforeAction' => function ($event) {
// default theme is 'light'
if(!Yii::$app->request->cookies->has('theme')){
Yii::$app->response->cookies->add(new Cookie([
'name' => 'theme',
'value' => 'light',
]));
}
},

然后我在AssetManager配置中重写bootstrap4:

'assetManager' => [
'bundles' => [
'yiibootstrap4BootstrapAsset' => [
'sourcePath' => null,
'basePath' => '@webroot',
'baseUrl' => '@web',
'css' => [
// override here
Yii::$app->getRequest()->getCookies()->getValue('theme') != 'dark' ?
(YII_ENV_DEV ? 'css/light/bootstrap.css' : 'css/light/bootstrap.min.css') :
(YII_ENV_DEV ? 'css/dark/bootstrap.css' : 'css/dark/bootstrap.min.css')
,
],
],

],
],

But i got error:

Fatal error: Uncaught Error: Call to a member function getRequest() on null in /var/www/html/config/web.php:71 Stack trace: #0 /var/www/html/web/index.php(10): require() #1 {main} thrown in /var/www/html/config/web.php on line 71

我认为我不能在配置中直接访问cookie。只是一个猜测,在config/web.php,可能是我需要引导,如'bootstrap' => ['log'],或定义一个新的全局变量,或另一个建议,你可以给我。

任何帮助或建议都是非常感谢的。

如果你在一个函数调用中包装你的css配置,它应该工作。

我尝试了两种方法,如果我尝试使用您的代码,我会得到Fatal error: Uncaught Error: Call to a member function getRequest() on null in /app/common/config/main.php:XX异常,但如果我将其更新为下面的代码,它就会起作用。

'assetManager' => [
'class' => 'yiiwebAssetManager',
'bundles' => [
'yiibootstrap4BootstrapAsset' => [
'sourcePath' => null,
'basePath' => '@webroot',
'baseUrl' => '@web',
'css' => static function () {
return [
// override here
Yii::$app->getRequest()->getCookies()->getValue('theme') != 'dark' ?
(YII_ENV_DEV ? 'css/light/bootstrap.css' : 'css/light/bootstrap.min.css') :
(YII_ENV_DEV ? 'css/dark/bootstrap.css' : 'css/dark/bootstrap.min.css')
,
];
},
],
],
],
'components' => [
// code...
'assetManager' => [
'class' => 'yiiwebAssetManager',
'bundles' => [
'yiibootstrap4BootstrapAsset' => [
'sourcePath' => null,
'basePath' => '@webroot',
'baseUrl' => '@web',
],
],
],
// code...
],
// code...
'on beforeRequest' => function ($event) {
Yii::$app->assetManager->bundles['yii\bootstrap4\BootstrapAsset'] = [
'css' => [
// override here
Yii::$app->getRequest()->getCookies()->getValue('theme') != 'dark' ?
(YII_ENV_DEV ? 'css/light/bootstrap.css' : 'css/light/bootstrap.min.css') :
(YII_ENV_DEV ? 'css/dark/bootstrap.css' : 'css/dark/bootstrap.min.css'),
],
];
},
'on beforeAction' => function ($event) {
// default theme is 'light'
if(!Yii::$app->request->cookies->has('theme')){
Yii::$app->response->cookies->add(new Cookie([
'name' => 'theme',
'value' => 'light',
]));
}
},
  • 请注意,服务器与cookie无关。浏览器负责完成这项工作。(作为请求的结果)
    因此,cookie的变化是不可见的,直到下一个页面重新加载(下一个请求)。