加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

php – 根据参数值Yii重写路由

发布时间:2020-12-13 22:54:28 所属栏目:PHP教程 来源:网络整理
导读:我在Yii中有几个规则允许我重写一些路由,其中??每个路由都将作为get参数传递给动作. 'department' = 'products/index','department/category' = 'products/index', 我想明确地写一个规则,根据参数值将URL更改为我想要的任何内容 例如,我现在有这样的URL www.
我在Yii中有几个规则允许我重写一些路由,其中??每个路由都将作为get参数传递给动作.

'<department>' => 'products/index','<department>/<category>' => 'products/index',

我想明确地写一个规则,根据参数值将URL更改为我想要的任何内容

例如,我现在有这样的URL
www.mysite.com/Books和Pencils因为这个规则’< department>‘而被重写=> ‘产品/索引’,这没关系

我想将该URL更改为www.mysite.com/books-pencils,如果有人知道如何编写比较deparment属性值的规则,然后将其重写为我想要的任何值.

谢谢

解决方法

您可以使用自定义类来处理特殊请求.
我使用过这样的方法,从数据库中获取自定义URL:

'urlManager'=>array(
            'rules'=>array(
                array(
                    'class' => 'application.components.UrlRule',),

然后你创建类似于这样的custo类:

<?php

Yii::import("CBaseRule");

class UrlRule extends CBaseUrlRule
{
    public function createUrl($manager,$route,$params,$ampersand)
    {
        // check for my special case of URL route,if not found,then return the unchaged route
        preg_match("/^(.+)/(.+)$/",$r);
        if(!is_array($r) or !isset($r[1]) or !isset($r[2])) {
            return $route;
        }

        // handle your own route request,and create your url
        $url = 'my-own-url/some-thing';

        // check for any params,which i also want to add
        $urlParams = $manager->createPathInfo($params,"=","&");

        $return = trim($url,'/');
        $return.= $urlParams ? "?" . $urlParams : "";

        return $return;
    }

    public function parseUrl($manager,$request,$pathInfo,$rawPathInfo)
    {

        // handle my special url request
        $controller = '....';
        $action = '.....';

        // return the controller/action that should be used     
        return lcfirst($controller)."/".$action;
    }
}

我不知道这是否是您想要的,但至少在本课程中,您可以使用所请求的URL完成所需的一切.
如果你愿意,想用301重定向到1个URL重定向很多类似的URL,你可以在parseUrl函数中想到这样的事情

// check my route and params,and if I need to redirect
$request->redirect('/your/new/url/?params=bla',true,'301');

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读