gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-10-31 23:40:02 25 4
gpt4 key购买 nike

我在 Yii 中有几条规则允许我重写一些路由,其中​​每个路由都将作为 get 参数传递给操作。

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

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

例如,现在我有一个这样的 URLwww.mysite.com/Books+%26+Pencils 因为这条规则被改写了'<department>' => 'products/index' , 没关系

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

谢谢

最佳答案

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

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

然后您创建与此类似的自定义类:

<?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("/^(.+)\/(.+)$/", $route, $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');

关于php - 根据参数值 Yii 重写路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28184034/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com