Sunday, September 9, 2012

Getting the 'protected' Directory's Parent in Yii

I needed the directory just above "protected." Here's how you do it:


Yii::getPathOfAlias('webroot')

Accessing a Module from Anywhere

I recently had the need to access the configuration variables for a module from within a controller that didn't own the module. It was a little frustrating that I was inside a widget that was a component of the module. Someone new to Yii or to MVC might assume, "Hey! I'm in the modules own widget. Why can't I get to the variables?" But think of it a bit like a stream: data moves down from controllers, which do the processing bits, and flow to relatively "dumb" things, like views which are only supposed to display, you know, stuff. If things were to move the other direction, it would like the stream getting backed up or even polluted. So, we keep things flowing in the right direction, letting the smarter parts of the app pass data down to the intentionally less smart parts.

All that being said, I *could* have passed the values to the widget - which is basically a view - but this was already a relatively poorly designed 3rd party module, and I just wanted to move forward. (This is also a very useful module that provides a lot of functionality that I'd prefer not to write myself, so I'm making modifications to get it to work a little better.) This meant finding some other way to gain access to some variables that had been set in the config file for the module. This is done like so:


// other Yii confi things go here, like components, import, etc

'import' => array(

      ...

),

'components' => array(

     ...

),

// and here is where the module goes

'modules' => array(

     'moduleName' => array(

          'moduleVar1' => 'value',

          'moduleVar2' => 'otherValue',

          'moduleArray' => array(
               'key' => 'val'
         ),

     ),

// More things happen here


In this example, I wanted to do something like find out what the value of "moduleVar1" was. There's a way to get at these sorts of things by basically starting from the top (the application level) and working your way down by using Yii::app(). Here, for example, is how you can see which modules are loaded across the entire application:


print_r(Yii::app()->getModules());


To get a specific module, you do this:

Yii::app()->getModule('moduleName');


To get the value for a variable from that module, you'd do this:

Yii::app()->getModule('moduleName')->moduleVar1


And actually, I had an array of values called 'config' like 'moduleArray' above, in which case I needed to get the value of a key of that array, like so:

Yii::app()->getModule('moduleName')->moduleArray['key']


Hope this helps someone.