Cannot get user in config/main.php. Why?

Hi,

I want to do some config in config/main.php, but while I can get a handle on Yii::app() there, I cannot get a handle on Yii::app()->user (or Yii::app()->getUser()) – both return null, even when the user is logged in.

First, why is Yii::app()->user not available at this point?

Second, where should I be doing "global" configuration that requires user if not in config/main.php?

Thanks,

Marc

Do not access any app component (including ‘user’) in config file because at this stage, app components are not configured yet.

You may consider putting your code in your base controller’s init() method.

Thanks for the (very passively voiced) suggestion, but…

Three things here:

  1. I’ve no need for a base controller class, so I’d rather not create one.

  2. I dislike the idea of an init() method in class, since that’s what a constructor is for.

The name “init()” doesn’t tell me, nor imply, what it’s doing.

  1. I only want to perform the start up operations once, and they are not controller specific.

Are you saying that there’s no hook at any point between Yii initialisation and messaging the first controller?

if you take a look at some other web application frameworks you’ll find that this is pretty much the same.

I have some experience with Cake and RoR and it’s exactly the same there.

Having in application controller actually makes a lot of sense because most of the time you’ll have some functionality that is shared by all controllers.

If you take it to the max you could possibly even put most of the CRUD functionality in the admin controller and just overwrite functions to get a specifc model instance.

There are other ways to do this. For example, you could respond to the onBeginRequest event of the application (you can attach to this event in app config). You could also extend CWebApplication. Using base controller’s init() is the easiest way to go.

The reason we introduce init() is because the signature of constructors could be complex, and if you override the constructor, you must call the parent implementation. Overriding init() doesn’t have these requirements.

Thanks very much. I’ve gone with a base controller. Thinking about it, there have been times where I’ve needed an intermezzo class like this, so it looks like the right way to go to me too! I also think that it’ll be useful for testing.

I also hadn’t realised that init() is invoke by Yii, so I was wondering how it was used.

I’m not sure why calling the parent constructor is an issue here, as you still have to call parent::init() in the controllers’ init() when using a base controller. But I can see that the constructor signatures could be a bit of a mess, so I understand the approach taken – I’m a pragmatist not a purist.