本文实例讲述了Yii全局函数用法。分享给大家供大家参考,具体如下:
由于YII致力于完美的整合第三方库,它并没有定义任何全局函数。yii中的每一个应用都需要全类别和对象范围。
例如,Yii::app()->user;Yii::app()->params['name'];等等。我们可以自行设定全局函数,使得代码看起来更加简洁易用。
我们可以保存在globals.php在protected/config目录下。然后,在入口脚本index.php中,定义如下内容:
$globals=dirname(__FILE__).'/protected/config/globals.php'
...
require_once($yii);
require_once($globals);
现在我们可以在应用的任何地方使用我们的全局函数,例如可以使用user()代替Yii::app()->user。注:如果你打算发布一个可重用的组件,请不要组件中使用全局函数,在不同的应用配置中,可能导致无法使用。同时,也应注意与第三方库的冲突,可考虑对每个函数前加上自己的前缀,已做区分,例如框架核心均已C为前缀。
下面是代码包含最常用的一些快捷功能。如还需其他,请自行添加。
代码如下 | 复制代码 |
/** * This is the shortcut to DIRECTORY_SEPARATOR */ defined('DS')ordefine('DS', DIRECTORY_SEPARATOR); /** * This is the shortcut to Yii::app() */ functionapp() { returnYii: :app(); } /** * This is the shortcut to Yii::app()->clientScript */ functioncs() { // You could also call the client script instance via Yii::app()->clientScript // But this is faster returnYii: :app() - >getClientScript(); } /** * This is the shortcut to Yii::app()->user. */ functionuser() { returnYii: :app() - >getUser(); } /** * This is the shortcut to Yii::app()->createUrl() */ functionurl($route,$params=array(),$ampersand='&') { returnYii: :app() - >createUrl($route,$params,$ampersand); } /** * This is the shortcut to CHtml::encode */ functionh($text) { returnhtmlspecialchars($text, ENT_QUOTES, Yii: :app() - >charset); } /** * This is the shortcut to CHtml::link() */ functionl($text,$url='#',$htmlOptions=array()) { returnCHtml: :link($text,$url,$htmlOptions); } /** * This is the shortcut to Yii::t() with default category = 'stay' */ functiont($message,$category='stay',$params=array(),$source= null,$language= null) { returnYii: :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. */ functionbu($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]. */ functionparam($name) { returnYii: :app() - >params[$name]; } /** * A useful one that I use in development is the following * which dumps the target with syntax highlighting on by default */ functiondump($target) { returnCVarDumper: :dump($target, 10, true); } |
敢达决战官方正版 安卓版v6.7.9
下载敢达决战 安卓版v6.7.9
下载像素火影骨架佐助 (Perseverance Fire Shadow)手机版v1.16
下载要塞英雄 安卓版v33.20.0-39082670-Android
下载梦想城镇vivo最新版本 安卓版v12.0.1
梦想城镇vivo版是这款卡通风模拟经营类手游的渠道服版本,玩
怦然心动的瞬间 安卓版v1.0
怦然心动的瞬间是一款真人向的恋爱互动游戏,在游戏中玩家将扮演
曼尼汉堡店游戏 安卓版v1.0.3
曼尼汉堡店是一款非常好玩的精品恐怖类型冒险游戏,在这款游戏中
现代总统模拟器去广告版 安卓版v1.0.46
现代总统模拟器是一款休闲养成类游戏,可能对于不少的玩家来说都
现代总统模拟器付费完整版 安卓版v1.0.46
现代总统模拟器高级版在商店是需要付费的,相对于普通版本,高级