helpers.md 1.68 KB
Newer Older
Qiang Xue committed
1 2 3
Helper Classes
==============

Larry Ullman committed
4
Yii provides many classes that help simplify  common coding tasks, such as string or array manipulations,
Larry Ullman committed
5
HTML code generation, and so forth. These helper classes are organized under the `yii\helpers` namespace and
Qiang Xue committed
6
are all static classes (meaning they contain only static properties and methods and should not be instantiated).
Larry Ullman committed
7 8


Larry Ullman committed
9
You use a helper class by directly calling one of its static methods:
Qiang Xue committed
10

Larry Ullman committed
11 12

```
Qiang Xue committed
13 14 15
use yii\helpers\ArrayHelper;

$c = ArrayHelper::merge($a, $b);
Qiang Xue committed
16
```
Qiang Xue committed
17 18 19 20

Extending Helper Classes
------------------------

Larry Ullman committed
21
To make helper classes easier to extend, Yii breaks each helper class into two classes: a base class (e.g. `BaseArrayHelper`)
Larry Ullman committed
22
and a concrete class (e.g. `ArrayHelper`). When you use a helper, you should only use the concrete version, never use the base class.
Qiang Xue committed
23

Larry Ullman committed
24
If you want to customize a helper, perform the following steps (using `ArrayHelper` as an example):
Qiang Xue committed
25

Larry Ullman committed
26
1. Name your class the same as the concrete class provided by Yii, including the namespace: `yii\helpers\ArrayHelper`
Larry Ullman committed
27 28
2. Extend your class from the base class: `class ArrayHelper extends \yii\helpers\BaseArrayHelper`.
3. In your class, override any method or property as needed, or add new methods or properties.
Larry Ullman committed
29
4. Tell your application to use your version of the helper class by including the following line of code in the bootstrap script:
Qiang Xue committed
30 31 32 33 34

```php
Yii::$classMap['yii\helpers\ArrayHelper'] = 'path/to/ArrayHelper.php';
```

Larry Ullman committed
35
Step 4 above will instruct the Yii class autoloader to load your version of the helper class instead of the one included in the Yii distribution.
Qiang Xue committed
36

Larry Ullman committed
37
> Tip: You can use `Yii::$classMap` to replace ANY core Yii class with your own customized version, not just helper classes.