helper-overview.md 2.2 KB
Newer Older
Qiang Xue committed
1 2 3
Helpers
=======

4
> Note: This section is under development.
Qiang Xue committed
5

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

You use a helper class by directly calling one of its static methods, like the following:
Qiang Xue committed
11 12

```php
Qiang Xue committed
13 14
use yii\helpers\Html;

Qiang Xue committed
15 16 17
echo Html::encode('Test > test');
```

Qiang Xue committed
18 19 20 21 22 23 24 25
> Note: To support [extending helper classes](#extending-helper-classes), Yii breaks each core helper class
  into two classes: a base class (e.g. `BaseArrayHelper`) and a concrete class (e.g. `ArrayHelper`).
  When you use a helper, you should only use the concrete version and never use the base class.


## Core Helper Classes

The following core helper classes are provided in the Yii releases:
Qiang Xue committed
26 27 28 29 30 31 32 33 34 35 36 37 38 39

- ArrayHelper
- Console
- FileHelper
- Html
- HtmlPurifier
- Image
- Inflector
- Json
- Markdown
- Security
- StringHelper
- Url
- VarDumper
Qiang Xue committed
40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75


## Extending Helper Classes

To custom a core helper class (e.g. `yii\helpers\ArrayHelper`), you should extend from its corresponding base class
(e.g. `yii\helpers\BaseArrayHelper`) and name your class the same as the corresponding concrete class
(e.g. `yii\helpers\ArrayHelper`), including its namespace.

The following example shows how to customize the [[yii\helpers\ArrayHelper::merge()|merge()]] method of the
[[yii\helpers\ArrayHelper]] class:

```php
namespace yii\helpers;

use yii\helpers\BaseArrayHelper;

class ArrayHelper extends BaseArrayHelper
{
    public static function merge($a, $b)
    {
        // your custom implementation
    }
}
```

Save your class in a file named `ArrayHelper.php`. The file can be in any directory, such as `@app/components`.

Next, in your application's [entry script](structure-entry-scripts.md), add the following line of code
after including the `yii.php` file:

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

The above line instructs the [Yii class autoloader](concept-autoloading.md) to load your version of the helper
class, instead of the one included in the Yii releases.