Yii 1.1: Use shortcut functions to reduce typing

48 followers

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()
{
    // You could also call the client script instance via Yii::app()->clientScript
    // But this is faster
    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()->getRequest()->getBaseUrl();
    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];
}

Links ΒΆ

Total 8 comments

#13068 report it
marcovtwout at 2013/05/01 09:21am
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

#7860 report it
Mike Stop Continues at 2012/04/23 04:32pm
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>';
    }
}
#6709 report it
marcovtwout at 2012/01/31 05:26am
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');
#6601 report it
yasen at 2012/01/20 05:54am
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;
}
#6056 report it
fsb at 2011/12/08 01:17pm
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.

#4774 report it
kokomo at 2011/08/14 08:20am
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();
}
#1989 report it
Orteko at 2010/10/26 11:18pm
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) ;
}
#1150 report it
Raoul at 2009/11/23 12:34pm
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.

Leave a comment

Please to leave your comment.

Write new article
  • Written by: qiang
  • Updated by: Yang He
  • Category: Tutorials
  • Yii Version: 1.1
  • Votes: +56
  • Viewed: 40,435 times
  • Created on: May 8, 2009
  • Last updated: Jun 29, 2012