Problem With Code Before All Actions

I have a problem with code which should be before every action.

For this I extended the controllers with a new BaseController.

This BaseController extends the yii-Controller and has the action

action().


class FooController extends BaseController

{

    public function actionIndex($id){

	echo $id;

	}


}


class BaseController extends \yii\base\Controller

{

    public function actions(){

	echo "code before every action";

	}


}

In this is action the code before every action is implemented. This works fine.

But the problem is:

The actions in the other controllers gets parameters from URL, like id

e.g. www.foo.bar/index.php?id=1

The action


actionIndex($id)

does not get the "1" any more. Without the new BaseController it works fine…

Can someone help me?

Use beforeAction(), not actions():

See documentation:

http://www.yiiframework.com/doc-2.0/yii-base-controller.html#beforeAction()-detail

vs.

http://www.yiiframework.com/doc-2.0/yii-base-controller.html#actions()-detail

Thanks, but I have still the problem to get the parameter from URL.

I changed the code to:


class BaseController extends \yii\base\Controller {


    public function beforeAction($action) {

        if (parent::beforeAction($action)) {

            echo "before";

            // your custom code here

            return true;  // or false if needed

        } else {

            return false;

        }

    }

}

The problem I did not get the "id" from URL:

in


class SiteController extends BaseController

{

    

    public function actionIndex($id = null)

    {       

     

        echo $id ;

       

    }

}

If I don’t extend BaseController, but Yii Controller it works fine:


class SiteController extends \yii\base\Controller

{

    

    public function actionIndex($id = null)

    {       

     

        echo $id ;

       

    }

}

Yii::$app->request->get(‘id’) will give the ID parameter or null if none is given.

http://www.yiiframework.com/doc-2.0/yii-web-request.html#get()-detail

Thanks…