Search code examples
yiifront-controller

Yii Front Controller Implementation before Routing


I want to implement a language Setter for all Controllers and need to run this method before the Routing to the Controller -> the front Controller.

If have implemented a method in my Controller Class, but for some usages it must be run earlier before controller initilisation

class Controller extends CController
{
  public function __construct($id, $module = null)
  {


    // Set the application language 

    if (isset($_GET['language']))
    {
        $lang = $_GET['language'];

Solution

  • You could use the onBeginRequest event of the application. This usually requires you to add some code to your index.php. Here's a quick example:

    $app = Yii::createWebApplication($config);
    $app->onBeginRequest = function($event) {
        // ... whatever you want to do
    }
    $app->run();
    

    Of course instead of a closure function you can also attach any other valid callback.