1

私は Yii Framework をベースにした REST API を持っています: http://www.yiiframework.com/wiki/175/how-to-create-a-rest-api/

次のように、Url ルールに API のバージョンを追加したいと思います。

array('api/view', 'pattern'=>'api/<version:\d+>/<model:\w+>/<id:\d+>', 'verb'=>'GET'),

どうすればいいですか?

4

2 に答える 2

4

1 つのコントローラーを使用する場合は、これまでと同じようにルールを維持できます。

array('api/view', 'pattern'=>'api/<version:\d+>/<model:\w+>/<id:\d+>', 'verb'=>'GET'),

コントローラーのアクションでバージョンを確認します。

public function actionView()
{
    // Check the version
    if($_GET['version'] == 1)
    {
       //do what you've got to do
    }
    else if ($_GET['version'] == 2)
    {
       //do what you've got to do
    }
}

別の解決策は、カスタム URL ルール機能を使用することです

  • メソッド「parseUrl」では、URL がルール (api/version/model/id がある) と一致するかどうかを確認し、API バージョンに応じて一致する場合は、適切なコントローラー (例: apiV2/view) にリダイレクトします。

コード:

public function parseUrl($manager,$request,$pathInfo,$rawPathInfo)
{
   if (preg_match('%^(api/(\d+))(/(\w+))(/(\d+))$%', $pathInfo, $matches))
        {
            // $matches[2] is the version and $matches[4] the model
            // If it matches we can check the version api and the model
            // If it's ok, set $_GET['model'] and/or $_GET['id']
            // and return 'apiVx/view'
        }
        return false;  // this rule does not apply
    }
于 2012-10-19T09:56:39.047 に答える