Yii - 从 URL 中删除模块的默认控制器 ID


Yii - Eliminate default controller ID for a module from URL

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

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

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

注意:我希望仅对默认控制器执行此操作。

谢谢

这有点棘手,因为操作部分可能被视为控制器,或者您可能指向现有控制器。但是,您可以使用自定义 URL 规则类来解决此问题。这是一个例子(我测试了它,它似乎运行良好(:

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;
  }
}