Global Event

Hi, I wrote this simple code :





	public static function setDefault($clientName)

	{

		$session = Yii::$app->session;

		$url = Yii::$app->urlManager->createUrl('client/change');

		

		$session->open();

		

		if (isset($session->client_id)) {

			if (($c = Client::find($session->client_id)) === null) {

				Yii::$app->getResponse()->redirect($url);

			}

			else {

				$session->client_id = $c->id;

				$session->client = $c->name;

			}

		}

		else {

			Yii::$app->getResponse()->redirect($url);

		}

	}



This idea is :

if "client_id" variable is defined in session, check if the value existe in DB, if not => redirection to client/change

If "client_id" variable is not defined => redirection to client/change

My questions are :

  • Wich event use ? beforeAction ? afterRequest ?

  • Where put this code ? Controller ? Model ? somethings else ?

  • How to check the current request route (not redirect if I’m in client/change, to avoid loop)

Thanks you for your help

I’d go with action filters.

So

  • behavior

  • filter + controller (see AccessControl as an example)

  • echo $this->createUrl(’’); // currently active route

I suppose you should also remove invalid client ID from session before redirecting.

Thanks you.

Somethings to know :

To get the current route, you need to do :




$action->getUniqueId();



The createUrl function return the full url (with the index.php?r=)