Home > Article > Backend Development > Yii controller action parameter binding processing_PHP tutorial
Starting from version 1.1.4, Yii provides support for automatic action parameter binding. That is, controller actions can define named parameters whose values will be automatically populated by Yii from $_GET.
To illustrate this functionality in detail, assume we need to write a create action for PostController. This action requires passing two parameters via $_GET:
category: an integer representing the ID of the category in which the post is to be published.
language: A string representing the language code used by the post.
When extracting parameters from $_GET, we can no longer write the relevant verification code like the following:
class PostController extends CController{ public function actionCreate(){ if(isset($_GET['category'])) $category=(int)$_GET['category']; else throw new CHttpException(404,'invalid request'); if(isset($_GET['language'])) $language=$_GET['language']; else $language='en'; // ...... } }
Now using the action parameter function, we can more easily complete tasks related to the above code:
class PostController extends CController{ public function actionCreate($category, $language='en'){ $category = (int)$category; echo 'Category:'.$category.'/Language:'.$language; // ...... } }
Note that we added two parameters to the action method actionCreate. The names of these parameters must match the names we want to extract from $_GET. When the user does not specify the $language parameter in the request, this parameter will use the default value en . Since $category has no default value, if the user does not provide the category parameter in $_GET, a CHttpException (error code 400) will be automatically thrown.
Starting from version 1.1.5, Yii already supports array action parameters. How to use:
class PostController extends CController{ public function actionCreate(array $categories){ // Yii will make sure $categories be an array } }