create constants usings yii parameters

A better approach when creating your application is to use parameters defined in the config options

Altho I really dont like to type everytime


$src=Yii::app()->params['public_url']."ex.jpg";

so I came with this code you code use to use some of your defined params as constants, a much easier way to read/write your code. You can use a parameters like this instead




echo PUBLIC_URL."ex.jpg";



and set the constants in your config options like this:




'params'=>array(

        	'_constant'=>array(

         		'public_path'=>realpath(__DIR__."../publico"),

   	      	'public_url'=>'/publico',

 				'layout_path'=>'{public_path}/layouts',

         		'layout_url'=>'{public_url}/layouts',

         		'js_url'=>'{public_url}/js/',

 				'css_url'=>'{public_url}/css/',

    	),



the code inside {} will be replaced by some other defined constant

Personally I like a lot to use the event "onBeginRequest" that Yii has.

In my case I added this code to the onBeginRequest event code, but you can attach this wherever you want tho:




    	//turn all _constant params into constants, like public_url index will become a constant PUBLIC_URL

    	//also threat dependencies like {public_url}/layouts will use the public_url constant to generate the value

    	foreach(Yii::app()->params['_constant'] as $key=>$constant){

        	if(preg_match("/\{(\w+)*\}/i",$constant,$r_constant)){

            	$constant=str_replace($r_constant[0],constant(strtoupper($r_constant[1])),$constant);

        	}

        	if(!defined(strtoupper($key)))

            	define(strtoupper($key),$constant);

    	}



and thats it.

If you have never used the "onBeginRequest" here is how you should do it :




	'onBeginRequest' => array('Bootstrap', 'beginRequest'),

	// application components

	'components'=>array('....'),



and create a bootstrap class with a method beginRequest




class Bootstrap

{

	public function beginRequest($event){

  	//the code here

	}

}