You are viewing revision #4 of this wiki article.
This version may not be up to date with the latest version.
You may want to view the differences to the latest version or see the changes made in this revision.
Because Yii intends to be integrated nicely with third-party libraries, it does not define any global functions. Everything in Yii needs to be addressed with full class name or object scopes. For example, to access the current user, we need to use Yii::app()->user
; to access application parameters, we need Yii::app()->params['name']
; and so on. While editors like textmate
can help alleviate the problem of these lengthy typings, it is worthwhile to define global shortcut functions to some commonly used method calls. They will make the application code look cleaner.
We may save the definition to these shortcut functions in a file named globals.php
under the protected
directory. Then, in the entry script index.php
, we include the file at the beginning:
require('path/to/globals.php');
require('path/to/yii.php');
......
Now, we can use these global functions anywhere in our application code. For example, to access the current user, we can use user()
, instead of the lengthy Yii::app()->user
.
Note: Do not use these shortcut functions in components that you intend to release as reusable extensions. Doing so would make your components unusable if the shortcut functions used are not defined in a different application. Also pay attention if the shortcut functions cause conflict with third-party libraries used in the application.
Below is the code containing some of the most commonly used shortcut functions. Feel free to adjust it according to your taste.
/**
* This is the shortcut to DIRECTORY_SEPARATOR
*/
defined('DS') or define('DS',DIRECTORY_SEPARATOR);
/**
* This is the shortcut to Yii::app()
*/
function app()
{
return Yii::app();
}
/**
* This is the shortcut to Yii::app()->clientScript
*/
function cs()
{
return Yii::app()->getClientScript();
}
/**
* This is the shortcut to Yii::app()->user.
*/
function user()
{
return Yii::app()->getUser();
}
/**
* This is the shortcut to Yii::app()->createUrl()
*/
function url($route,$params=array(),$ampersand='&')
{
return Yii::app()->createUrl($route,$params,$ampersand);
}
/**
* This is the shortcut to CHtml::encode
*/
function h($text)
{
return htmlspecialchars($text,ENT_QUOTES,Yii::app()->charset);
}
/**
* This is the shortcut to CHtml::link()
*/
function l($text, $url = '#', $htmlOptions = array())
{
return CHtml::link($text, $url, $htmlOptions);
}
/**
* This is the shortcut to Yii::t() with default category = 'stay'
*/
function t($message, $category = 'stay', $params = array(), $source = null, $language = null)
{
return Yii::t($category, $message, $params, $source, $language);
}
/**
* This is the shortcut to Yii::app()->request->baseUrl
* If the parameter is given, it will be returned and prefixed with the app baseUrl.
*/
function bu($url=null)
{
static $baseUrl;
if ($baseUrl===null)
$baseUrl=Yii::app()->request->baseUrl;
return $url===null ? $baseUrl : $baseUrl.'/'.ltrim($url,'/');
}
/**
* Returns the named application parameter.
* This is the shortcut to Yii::app()->params[$name].
*/
function param($name)
{
return Yii::app()->params[$name];
}
translator
If you use t(), then forget about using yiic message to extract messages because it assumes that message category is the first parameters (like with yii::t) ..with t(), category is the second parameter.
Dump shortcut
A useful one that I use in development is the following which dumps the target with syntax highlighting on by default:
function dump($target) { return CVarDumper::dump($target, 10, true) ; }
Additional session shortcut functions
I use the following additional session shortcut functions.
function sess($key = null, $value = null) { if (!empty ($key) && !empty ($value)) { return Yii::app()->session[$key] = $value; } elseif (!empty ($key)) { return Yii::app()->session[$key]; } else { return Yii::app()->session; } } function getSessArr() { return sess()->toArray(); } function getSessId() { return sess()->sessionID; } function regenSessId() { return sess()->regenerateId(); } function printSess() { echo '<pre>'; foreach (getSessArr() as $key => $value) { echo ' '.$key .' -> '.$value.'<br/>'; } echo '</pre>'; } function removeSess($key) { return sess()->remove($key); } function destroySess() { return sess()->destroy(); }
Add @return tages
If you add PHPDoc tags, especially @return, to these shortcuts then your IDE (PhpStorm, Netbeans, Eclipse, etc.) knows how to validate and code complete your code that uses them.
My version of this file does that and it's really handy.
image, dump and die
/** * @return string the generated image tag */ function i($src, $alt='', $htmlOptions=array()) { return CHtml::image($src, $alt, $htmlOptions); } /** * Dump and die - extending dump() from post #7860 */ function dd() { $args = func_get_args(); foreach($args as $k => $arg){ echo '<fieldset class="debug"> <legend>'.($k+1).'</legend>'; CVarDumper::dump($arg, 10, true); echo '</fieldset>'; } die; }
Including globals.php
You can also include it in your config file, instead of modifying all your bootstrap files.
require(dirname(__FILE__).'/../helpers/globals.php');
New dump()
This dump will accept as many arguments as you through at it, and wraps the content for styling (and js folding).
The only thing I couldn't figure out was how to get the names of the arguments passed to give them proper labels. If one of you knows, please share! But otherwise, the numbering helps for when you dump inside of a loop and want to know where one loop ends and the next begins.
Enjoy!
/** * Dump as many variables as you want. Infinite parameters. */ function dump() { $args = func_get_args(); foreach($args as $k => $arg){ echo '<fieldset class="debug"> <legend>'.($k+1).'</legend>'; CVarDumper::dump($arg, 10, true); echo '</fieldset>'; } }
Consider using code templates
Shortcuts functions can be handy in some cases, but can be very unhandy when dealing with larger developer groups or when sharing code. Consider using code templates in your IDE instead, where shortcut strings are automatically expanded to the full code. (for example, I type 'ya -TAB-' and get 'Yii::app()->')
See: http://www.yiiframework.com/wiki/83/netbeans-ide-and-yii-projects/#hh1
If you have any questions, please ask in the forum instead.
Signup or Login in order to comment.