1

我是 Yii 的新手,我正在尝试实现 parseUrl 来管理 url 上的 API 版本。我想将 /api/1.0/... 重定向到控制器 apiV1.0。

Main.php(urlManager 规则):

...
array('class' => 'application.components.ApiVersion'),
...

ApiVersion.php:

<?php
    class ApiVersion extends CBaseUrlRule
    {
    public $connectionID = 'db';

    public function createUrl($manager,$route,$params,$ampersand)
    {
        if ($route==='car/index')
        {
            if (isset($params['manufacturer'], $params['model']))
                return $params['manufacturer'] . '/' . $params['model'];
            else if (isset($params['manufacturer']))
                return $params['manufacturer'];
        }
        return false;  // this rule does not apply
    }

    public function parseUrl($manager,$request,$pathInfo,$rawPathInfo)
    {
        if (preg_match('%^(\w+)(/(\w+))?$%', $pathInfo, $matches))
           $url =  $match[1] .  $match[2]; // BUILD YOUR URL (controllerName/actionName)
           $this->redirect(array($url));
        }
        return false;
    }
}

我对它的工作原理非常迷茫,有人可以帮助我吗?

4

1 回答 1

1

在您的函数中,正则表达式检查路径是否类似于“api/num_of_version/your_model/an_id”

因此,如果您的 url 与您的条件匹配,则必须设置 get 值:

$_GET['apiversion'] = $matches[2];
$_GET['model'] = $matches[4];
$_GET['id'] = $matches[6];

并根据您返回良好控制器的版本:

return "apiV" . $_GET['apiversion'] . "/view";

您需要了解的一些链接:

编辑:如果您在某个特定点遇到麻烦,请现在告诉我,我将尝试详细说明我在这一点上的回答。

于 2012-10-26T08:03:50.357 回答