0

我有一个带有前端和后端的 yii 高级应用程序。

我试图实现的是我可以使用客户的名字访问前端。

示例(本地):http://localhost/myproject/frontend/web/customer1应该成为http://localhost/myproject/frontend/web/customer1/site/login第一次访问

登录后,客户的姓名应保留在 URL 中。目前,登录后URL更改为http://localhost/myproject/frontend/web/

信息: customer是一个 GET 参数。它应该始终是之后的第一个参数,http://localhost/myproject/frontend/web/但我不想在每个重定向或自定义链接中指定参数。我希望有一种方法可以保留此参数并将其传递给以下每个站点更改。

到目前为止我已经尝试过:

'urlManager' => [
            'class' => 'yii\web\UrlManager',
            'enablePrettyUrl' => true,
            'showScriptName' => false,
            'enableStrictParsing' => true, 
            'rules' => [
                '<controller>/<action>' => '<controller>/<action>',
                '<customer:\w+>' => '/site/login',
            ]
        ],

但这不起作用。我只能访问登录页面,之后客户名称不再显示在 URL 中。

我的 .htaccess 文件如下所示:

RewriteEngine on

# If a directory or a file exists, use it directly
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# Otherwise forward it to index.php
RewriteRule . index.php

我非常感谢有关此主题的任何提示。

4

1 回答 1

1

要将客户名称添加到所有 url,请修改您的 url 规则:

<customer:\w+>/<controller>/<action>' => '<controller>/<action>,

如果您现在调用yii\helpers\Url::to(['site/index', 'customer' => 'customer'])输出将如您所愿 - /customer/site/index

Howewer 在整个项目中这样称呼它不是灵活的方法。

大多数时候Url::to()方法用于生成内部 url。

如果你传入数组$route,它会调用Url::toRoute(). 因此,您可以简单地在自定义组件中覆盖该方法。

namespace frontend\components;

use yii\helpers\Url as BaseUrl;

class Url extends BaseUrl
{
    public static function toRoute($route, $scheme = false)
    {
        $customer = ... // Get saved after login customer name (for example from the session)
        $route['customer'] = $customer;

        return parent::toRoute($route, $scheme);
    }
}

然后你可以简单地调用frontend\components\Url::to(['site/index'])来达到相同的结果。

此处官方文档中描述的自定义帮助程序类的替代方法。

更新:

此外,此 url 规则'<customer:\w+>' => '/site/login',是多余的,并且 url 应该是 just site/login,因为登录之前的任何用户都是访客。

于 2015-01-23T18:25:55.890 回答