由于YII致力于完美的整合第三方库,它并没有定义任何全局函数。yii中的每一个应用都需要全类别和对象范围。
例如,Yii::app()->user;Yii::app()->params['name']
;等等。我们可以自行设定全局函数,使得代码看起来更加简洁易用。
我们可以保存在globals.php在protected目录下。然后,在入口脚本index.php的,我们包括在开始文件
require('path/to/globals.php'); require('path/to/yii.php');
现在我们可以在应用的任何地方使用我们的全局函数,例如可以使用user()代替Yii::app()->user。 注:如果你打算发布一个可重用的组件,请不要组件中使用全局函数,在不同的应用配置中,可能导致无法使用。 同时,也应注意与第三方库的冲突,可考虑对每个函数前加上自己的前缀,已做区分,例如框架核心均已C为前缀。
下面是代码包含最常用的一些快捷功能。
01
|
/**
|
02
|
* This is the shortcut to DIRECTORY_SEPARATOR
|
03
|
*/
|
04
|
defined(
'DS'
)
or
define(
'DS'
,DIRECTORY_SEPARATOR);
|
05
|
06
|
/**
|
07
|
* This is the shortcut to Yii::app()
|
08
|
*/
|
09
|
function
app()
|
10
|
{
|
11
|
return
Yii::app();
|
12
|
}
|
13
|
14
|
/**
|
15
|
* This is the shortcut to Yii::app()->clientScript
|
16
|
*/
|
17
|
function
cs()
|
18
|
{
|
19
|
// You could also call the client script instance via Yii::app()->clientScript
|
20
|
// But this is faster
|
21
|
return
Yii::app()->getClientScript();
|
22
|
}
|
23
|
24
|
/**
|
25
|
* This is the shortcut to Yii::app()->user.
|
26
|
*/
|
27
|
function
user()
|
28
|
{
|
29
|
return
Yii::app()->getUser();
|
30
|
}
|
31
|
32
|
/**
|
33
|
* This is the shortcut to Yii::app()->createUrl()
|
34
|
*/
|
35
|
function
url(
$route
,
$params
=
array
(),
$ampersand
=
'&'
)
|
36
|
{
|
37
|
return
Yii::app()->createUrl(
$route
,
$params
,
$ampersand
);
|
38
|
}
|
39
|
40
|
/**
|
41
|
* This is the shortcut to CHtml::encode
|
42
|
*/
|
43
|
function
h(
$text
)
|
44
|
{
|
45
|
return
htmlspecialchars(
$text
,ENT_QUOTES,Yii::app()->charset);
|
46
|
}
|
47
|
48
|
/**
|
49
|
* This is the shortcut to CHtml::link()
|
50
|
*/
|
51
|
function
l(
$text
,
$url
=
'#'
,
$htmlOptions
=
array
())
|
52
|
{
|
53
|
return
CHtml::link(
$text
,
$url
,
$htmlOptions
);
|
54
|
}
|
55
|
56
|
/**
|
57
|
* This is the shortcut to Yii::t() with default category = 'stay'
|
58
|
*/
|
59
|
function
t(
$message
,
$category
=
'stay'
,
$params
=
array
(),
$source
=null,
$language
=null)
|
60
|
{
|
61
|
return
Yii::t(
$category
,
$message
,
$params
,
$source
,
$language
);
|
62
|
}
|
63
|
64
|
/**
|
65
|
* This is the shortcut to Yii::app()->request->baseUrl
|
66
|
* If the parameter is given, it will be returned and prefixed with the app baseUrl.
|
67
|
*/
|
68
|
function
bu(
$url
=null)
|
69
|
{
|
70
|
static
$baseUrl
;
|
71
|
if
(
$baseUrl
===null)
|
72
|
$baseUrl
=Yii::app()->getRequest()->getBaseUrl();
|
73
|
return
$url
===null ?
$baseUrl
:
$baseUrl
.
'/'
.ltrim(
$url
,
'/'
);
|
74
|
}
|
75
|
76
|
/**
|
77
|
* Returns the named application parameter.
|
78
|
* This is the shortcut to Yii::app()->params[$name].
|
79
|
*/
|
80
|
function
param(
$name
)
|
81
|
{
|
82
|
return
Yii::app()->params[
$name
];
|
83
|
}
|
84
|
/**
|
85
|
* A useful one that I use in development is the following
|
86
|
* which dumps the target with syntax highlighting on by default
|
87
|
*/
|
88
|
function
dump(
$target
)
|
89
|
{
|
90
|
return
CVarDumper::dump(
$target
, 10, true) ;
|
91
|
}
|