Validate Action Parameters In An Elegant Way

I have a few actions that all have a parameter that should be an int. So all these actions start with the same few lines of code to test that what is passed is actually an int, and if not then an error is thrown:

    public function actionAbc($c) {


        if (!filter_var($c, FILTER_VALIDATE_INT))

            throw new CHttpException(404);

    //more code here



Is there a more elegant way to write such code ? I guess this can be done with a filter that examines $_GET[‘c’] ? And then add that filter to the controller for all the actions with that signature ?

Thoughts ?

A filter fits perfectly in that scenario.

There are a few problems with using filter_var:

  • It is limited to a max integer size of PHP_INT_MAX

  • It doesn’t allow leading zeros

  • Data passed by GET and POST is a string, anyway

Note that Yii does not automatically cast action parameters to a specific type. (Source). If you really need integers, and not strings of integers, you’ll need to cast them in either a filter or action.

Anyways, here’s how you’d solve your exception problem with a filter:


class Controller


    public function filters()


        return array(

            'cIsInteger +view, edit, delete',




    public function filterCIsInteger($filterChain)


        if (isset($filterChain->controller->actionParams['c'])) {

            $c = $filterChain->controller->actionParams['c'];

            if (!preg_match('#^\d+$#', $c)) {

                throw new CHttpException(400, 'C must be an integer.');



        return $filterChain->run();



Thank you!

I will go for that route then.