Best Place To Put Application Initialization Code

I’m brand new to YII so go easy on me.

I’m writing an application that’s essentially a web services client. It has two initial logins. One for the application itself and another for users.

The application login doesn’t require prompts (will get credentials from config) and must happen successfully before anything else can happen.

Basically I need to call this app login service very early on. What is the best place for this? Extend the Application class? Put in botstrap script? etc.


there is an event application.onBeginRequest, in your config/main.php you can write something like this:

'onBeginRequest' => function ($event) {var_dump($this, $event)},

Do you know if the interface is shown at this point? In other words what means do I have to show an error if there is one?

I think the easiest way is to put login logic in some file and include that file in config or boot file… Not sure if it’s the clearest way tho :)


Basically you need two authentications right? one is whole application authentication and the other is user login.

For the whole application authentication you can set a session separately. That can be done by extending CBehaviour class do the stuffs as follows in the components folder the class and file name must be same.

class RequireLogin extends CBehavior{

public function attach($owner) {

        $owner->attachEventHandler('onBeginRequest', array($this, 'handleBeginRequest')); // handleBeginRequest is the function where you can define the sessions.


public function handleBeginRequest($event) {

   	//Set your own whole application authentication session var here and check 


		//Read your config and set the sessions

		Yii::app()->session['whole_app_auth'] = 'value'; 

		//Redirect script for further user authentication web service page... and stuffs...




Don’t forget to add the following code into your config file

'behaviors' => array(

        'onBeginRequest' => array(

            'class' => 'application.components.RequireLogin' // points your class file and stuffs



For user login

check the yii’s default isGuest property and you may do the checkpoint in beforeAction of the controller.php file. example

if (Yii::app()->user->isGuest){

	 //The user need to login


	return true; 

Let me know if any clarifications needed further…

I think it will work!


Yes two auths. I will try this, though being so new, I don’t yet follow everything you mentioned. I’ll let you know how it goes.


This did work. I can do the global app login as well as set which pages the user auth is required.

Thanks for the help.

Don’t forget to press +