Yiiを使ってcmsのようなアプリを作ろうとしています。機能は次のようになります。
http://www.example.com/article/some-article-name
私がやろうとしているのは、すべてを のメソッドactionIndex()に渡しArticleController.php、その 1 つのメソッドでアクションの処理方法を決定することです。私の質問は、Yii のコントローラーですべてのアクションを 1 つのメソッドにルーティングするにはどうすればよいですか?
Yiiを使ってcmsのようなアプリを作ろうとしています。機能は次のようになります。
http://www.example.com/article/some-article-name
私がやろうとしているのは、すべてを のメソッドactionIndex()に渡しArticleController.php、その 1 つのメソッドでアクションの処理方法を決定することです。私の質問は、Yii のコントローラーですべてのアクションを 1 つのメソッドにルーティングするにはどうすればよいですか?
あなたの場合、フィルターまたはbeforeActionメソッドのどちらかを使用する方が良いと思います。
フィルター方法:
フィルターは、コントローラー アクションの実行前および/または実行後に実行されるように構成されたコードです。
サンプル:
class SomeController extends Controller {
// ... other code ...
public function filters() {
return array(
// .. other filters ...
'mysimple', // our filter will be applied to all actions in this controller
// ... other filters ...
);
}
public function filterMysimple($filterChain) { // this is the filter code
// ... do stuff ...
$filterChain->run(); // this bit is important to let the action run
}
// ... other code ...
}
beforeAction仕方:
このメソッドは、アクションが実行される直前 (考えられるすべてのフィルターの後) に呼び出されます。このメソッドをオーバーライドして、アクションの最後の準備を行うことができます。
サンプル:
class SomeController extends Controller {
// ... other code ...
protected function beforeAction($action) {
if (parent::beforeAction($action)){
// do stuff
return true; // this line is important to let the action continue
}
return false;
}
// ... other code ...
}
補足として、この方法でもコントローラー内の現在のアクションにアクセスできます : $this->action、の値を取得するid: $this->action->id:
if($this->action->id == 'view') { // say you want to detect actionView
$this->layout = 'path/to/layout'; // say you want to set a different layout for actionView
}
config の urlManager ルールの先頭にこれを追加します。
'article/*' => 'article',