温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

全局函数怎么在Yii中使用

发布时间:2020-12-30 15:48:43 阅读:125 作者:Leah 栏目:开发技术
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

这期内容当中小编将会给大家带来有关全局函数怎么在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'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];
}
/**
* 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($target10true);
}

上述就是小编为大家分享的全局函数怎么在Yii中使用了,如果刚好有类似的疑惑,不妨参照上述分析进行理解。如果想知道更多相关知识,欢迎关注亿速云行业资讯频道。

亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

yii
AI

开发者交流群×