Accessing the controller in writeSession in class extending CDbHttpSession

Hi,

I have created a class that extends CDbHttpSession. In this class I override the method writeSession. I want to access the currently used controller.

When I try to access the controller like this Yii::app()->getController() in the method writeSession. The controller seems to be uninitialized at that point. I can access the user like this Yii::app()->user but not the controller. If I run Yii::app()->getController() in for instance the afterFind method of the model it works just fine.

Is this by design or should I be able to run Yii::app()->getController() from within writeSession ?

What I want to do is get hold of the page title for the controller and save it in a separate column in the session table. This way I can see what page every logged in user is currently accessing.

/John

I don't think writeSession is a good place to go because it may occur when there is no controller yet.

A simpler approach is to create a base controller class and override its init() method. In this method, you can update the session table according to the current user session id.

That is actually exactly what I have done since the write session approach didn't work. I am not updating the table directly from the init method, instead I am setting a session variable and check for if this variable is available in writeSession. I have updated the sql query in writeSession method to include the pageTitle string in a separate column. This way I only have to write to the session table once.

What do you think about that approach? Maybe it is better to write to the session table directly from the init method of the extended controller?

I think either is fine.

I think so too.

Unfortunately I discovered the running $this->getPageTitle() in init is not a very good idea. If you do that the page title will say "blog - Post" for the show action for Posts. If $this->getPageTitle() is not run in init it will say "blog - Show Post".

If I override afterAction and move the functionality there it works as expected. Since afterAction takes an action as parameter it doesn't feel right to do this in afterAction. Maybe there should be a method exit() that we can override just like init? After action was the closest I could find to an exit method?

For your case, I agree that init() is not a good place because your page title may not be ready yet. afterAction() should be fine. The $action parameter is given for convenience. You don't need to use it.

I agree, and it kind of makes sense to put it in afterAction because we actually need the action name as input to be able to show the whole page title that includes the action name.

Thanks for the help now I know how to proceed.