Yii - 从 URL 中删除模块的默认控制器 ID [英] Yii - Eliminate default controller ID for a module from URL

查看:20
本文介绍了Yii - 从 URL 中删除模块的默认控制器 ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个模块,里面有一个默认控制器.现在我可以在/mymodule/等默认控制器中访问索引操作(默认操作).对于所有其他操作,我需要在 url 中指定控制器 ID,例如/mymodule/default/register/.我想知道是否可以从模块中默认控制器的 url 中删除控制器 ID.

I created a module and there exists a default controller inside that. Now I can access the index action (default action) in the default controller like /mymodule/. For all other action i need to specify the controller id in the url like /mymodule/default/register/ . I would like to know is it possible to eliminate the controller id from url for the default controller in a module.

我需要像这样设置 url 规则:

I need to set url rule like this:

before beautify : www.example.com/index.php?r=mymodule/default/action/

after beautify : www.example.com/mymodule/action/

注意:我希望这仅发生在默认控制器上.

Note: I want this to happen only for the default controller.

谢谢

推荐答案

这有点棘手,因为操作部分可能被视为控制器,或者您可能指向现有控制器.但是你可以通过使用 自定义 URL 规则类.这是一个例子(我测试过它似乎工作得很好):

This is a little tricky because the action part might be considered as a controller or you might be pointing to an existing controller. But you can get away with this by using a Custom URL Rule Class. Here's an example (I tested it and it seems to work well):

class CustomURLRule extends CBaseUrlRule
{
  const MODULE = 'mymodule';
  const DEFAULT_CONTROLLER = 'default';

  public function parseUrl($manager, $request, $pathInfo, $rawPathInfo)
  {
    if (preg_match('%^(\w+)(/(\w+))?$%', $pathInfo, $matches)) {
      // Make sure the url has 2 or more segments (e.g. mymodule/action)
      // and the path is under our target module. 
      if (count($matches) != 4 || !isset($matches[1]) || !isset($matches[3]) || $matches[1] != self::MODULE)
        return false;

      // check first if the route already exists
      if (($controller = Yii::app()->createController($pathInfo))) {
        // Route exists, don't handle it since it is probably pointing to another controller
        // besides the default.
        return false;
      } else {
        // Route does not exist, return our new path using the default controller.
        $path = $matches[1] . '/' . self::DEFAULT_CONTROLLER . '/' . $matches[3];
        return $path;
      }
    }
    return false;
  }

  public function createUrl($manager, $route, $params, $ampersand)
  {
    // @todo: implement
    return false;
  }
}

这篇关于Yii - 从 URL 中删除模块的默认控制器 ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆