【问题标题】:using url::to() in main.php file在 main.php 文件中使用 url::to()
【发布时间】:2021-07-11 20:27:37
【问题描述】:

在我的main.php 我有这个代码

  'authClientCollection' => [
            'class' => 'yii\authclient\Collection',
            'clients' => [

                'google' => [
                    'class' => 'Da\User\AuthClient\Google', 
                    'clientId' => 'xxxxxxxxxxxxxxxxxapps.googleusercontent.com',
                    'clientSecret' => 'xxxxxxxxxxxxxxxx',
                    'returnUrl' => Url::to(['user/security/auth', 'authclient' => 'google']], true),
                ],

但我得到了这个错误。

Notice: Trying to get property 'controller' of non-object in C:\xampp\htdocs\yii2\vendor\yiisoft\yii2\helpers\BaseUrl.php on line 136

我也试过\Yii::$app->urlManager->createAbsoluteUrl('user/security/auth', ['authclient' => 'google']),

得到了这个错误

Notice: Trying to get property 'urlManager' of non-object in C:\xampp\htdocs\yii2\frontend\config\main.php on line 160

如何在 main.php 中设置绝对 URL?谢谢

【问题讨论】:

  • 您不能在配置文件中使用Url::to()Yii::$app。配置文件甚至在创建应用程序实例之前就被处理,因为创建该实例需要配置。您应该简单地对 url 进行硬编码。如果您绝对需要使用 url manager 动态设置 url,您应该在创建应用程序实例后设置它。

标签: yii yii2


【解决方案1】:

您可以在main.phpon beforeRequest部分覆盖returnUrl或其他组件配置

'components' => [
    'google' => [
        'class' => 'Da\User\AuthClient\Google',
        'clientId' => 'xxxxxxxxxxxxxxxxxapps.googleusercontent.com',
        'clientSecret' => 'xxxxxxxxxxxxxxxx',
    ],
],
'on beforeRequest' => function ($event) {
    Yii::$app->google->returnUrl = Url::to(['user/security/auth', 'authclient' => 'google'], true);
},

Ref Link

  • 你也可以处理数据库

【讨论】:

  • 我收到了Getting unknown property: yii\web\Application::google
  • 您确定将“google”添加到“组件”中吗?
  • 是的,它在'components' => [ 'authClientCollection' => [ 'clients' => [ 'google' => [ .... ] ] ] ]
  • 试试这个> Yii::$app->authClientCollection->clients->google->returnUrl = Url::to()....
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-09
  • 2013-06-07
  • 1970-01-01
  • 2017-04-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多