Yii 2 Helpers
Yii 2 Helpers

Helpers

Note: This section is under development.

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).

Старт! Честный VDS/VPS, на котором «Лунная База» живет уже 20+ лет

Задумываетесь о том, чтобы поднять свой pet-проект, сайт клиента или настроить окружение для разработки? Уже пора подумать, где арендовать железо.

Лунная База хостится на FirstVDS более 20 лет. Мыслей о том, чтобы перебраться на другой хостинг, не было ни разу (хотя опыт работы с другими вариантами, конечно, есть).

Бывали разные ситуации, но они бывают на любом железе. Главное, что нужно понять: здесь нет маркетинговой шелухи и сказок про «мы всё сделаем за вас». Если вы берете VDS — вам дают полный root, возможность накатить любую ОС и не лезут в ваши конфиги.

Если в саппорт написать с вопросом по вашему коду и получить ответ: «Читайте документацию и разбирайтесь сами» или «Обратитесь к профильному специалисту» — это не повод обижаться. Это повод углубить свои знания в DevOps и сайтостроении! Бегите от тех, кто пообещает: «Мы всё чиним и настраиваем абсолютно бесплатно!». Никто никогда не работает «по доброте душевной» в ущерб себе, а бесплатный сыр в администрировании обычно заканчивается сломанной базой данных.

Что по факту: Гибкое масштабирование ядер и RAM, экономия по сравнению с физическими серверами и адекватная панель ispmanager, если она вам нужна.



You use a helper class by directly calling one of its static methods, like the following:

use yii\helpers\Html;

echo Html::encode('Test > test');

Note: To support customizing 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:

  • ArrayHelper
  • Console
  • FileHelper
  • FormatConverter
  • Html
  • HtmlPurifier
  • Imagine (provided by yii2-imagine extension)
  • Inflector
  • Json
  • Markdown
  • StringHelper
  • Url
  • VarDumper

Customizing Helper Classes

To customize a core helper class (e.g. [[yii\helpers\ArrayHelper]]), you should create a new class extending from the helpers 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. This class will then be set up to replace the original implementation of the framework.

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

<?php

namespace yii\helpers;

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, for example @app/components.

Next, in your application's entry script, add the following line of code after including the yii.php file to tell the Yii class autoloader to load your custom class instead of the original helper class from the framework:

Yii::$classMap['yii\helpers\ArrayHelper'] = '@app/components/ArrayHelper.php';

Note that customizing of helper classes is only useful if you want to change the behavior of an existing function of the helpers. If you want to add additional functions to use in your application, you may be better off creating a separate helper for that.

Самый честный хостинг за 20+ лет существования Лунной Базы

Задумываешься о том, чтобы поднять свой сайт в Интернете? Уже пора подумать о том, какой хостинг выбрать?

Лунная База хостится 20+ лет на firstDVS. При этом, мыслей о том, чтобы перебраться на другой хостинг не было. (Но, при этом есть опыт работы с другими вариантами.)

Бывали с firstDVS разные ситуации, но, они бывают на всех хостингах. Единственное, что тут важно понять, - это то, что никто ничего тебе не будет впаривать... Но, и работать за тебя тоже никто не станет. Если в саппорт ответили: «Читайте по ссылке и разбирайтесь сами...» или вообще «Обратитесь за помощью к специалисту», - это повод углубить свои знания в области сайтостроения, а не бежать к тем, что пообещают: «Мы всё чиним и всё делаем за своих клиентов абсолютно бесплатно!» Никто никогда ничего ни за кого "по доброте душевной" не делал, не делает и не будет делать!

Старт! MoonВase — A Hot Start on the Internet
Старт! MoonВase — A Hot Start on the Internet
Старт! Menu