Application wide variables, including views

I’m having trouble figuring out how to make some variables I need in views that are in essence global - are used in variety of views and passing then to the views all the time is just tedious.

I can’t use Yii::app()->params because those variables are dynamic and are based on current URL, so they are processed on application startup.

Essentially this is not only for views, but for the whole application itself (but I use those mainly in views). And the most part that makes it all suck - it’s a multi site application. One code base supporting 5 sites and growing. That’s why I need pure dynamic solution, but as clean as possible because the base will be used for other projects too.

If they are application wide you can define constants using ‘define’ function.

Have you looked at CWebUser::setState?

And it will not work for CConsoleCommand, because there is no CWebUser.

I know that there are ways. The thing is - we need some really global variables, witch are available at any workflow - be it WEB or CLI.

Make a component that you add to the application that stores and holds your global variables.

In your config, include it for both main and console configs, then you can access it from anywhere like

Yii::app()->mySharedStorage->propertyXYZ

Dana,

My trouble of global variable issue leads me to this post, but I tried your

application storage solution.

It doesn’t work for me. When I store the the info in an action, then the value is gone in another controller action.

Here is my storage:


Class Storage extends CApplicationComponent

{

	public $myCompany;

	public $myUser;

	

}

component init in main.php:


	'components'=>array(

            	'storage'=>array(

                	'class'=>'application.components.Storage',

                	'myCompany'=> null,

            	),

When the value is set, I use CVarDummper to confirm the value is set correctly, but in another controller/action, the value is null.

Do you know what’s going on?

Sorry, didn’t see this when it was originally posted.

It sounds like you’re running multiple page calls? The data will be reset between each page load if you’re storing it this way. This is really only useful for passing data between components during the same page call, unless you’re using a $this->forward() call on the controller.

If you want storage that persists between page loads, you should try setting it to the state for the user, using


Yii::app()->user->setState('myVariableName', $someValue);

I recently came across this: Set Global State

which might help across a single application.

The description reads:

It wasn’t clear from your original problem if you were looking for something by user (which Dana’s response handles) or something truly global at the application level.