当前位置: 移动技术网 > IT编程>开发语言>PHP > Yii全局函数用法示例

Yii全局函数用法示例

2017年12月12日  | 移动技术网IT编程  | 我要评论

儿童服装搭配,csol佳佳,安丘新闻网

本文实例讲述了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($target, 10, true);
}

更多关于yii相关内容感兴趣的读者可查看本站专题:《yii框架入门及常用技巧总结》、《php优秀开发框架总结》、《smarty模板入门基础教程》、《php面向对象程序设计入门教程》、《php字符串(string)用法总结》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总

希望本文所述对大家基于yii框架的php程序设计有所帮助。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网