Application Components Yii 2
Application Components Yii 2

Application Components

Applications are service locators. They host a set of the so-called application components that provide different services for processing requests. For example, the urlManager component is responsible for routing Web requests to appropriate controllers; the db component provides DB-related services; and so on.

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

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

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

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

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

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



Each application component has an ID that uniquely identifies itself among other application components in the same application. You can access an application component through the expression:

\Yii::$app->componentID

For example, you can use \Yii::$app->db to get the [[yii\db\Connection|DB connection]], and \Yii::$app->cache to get the [[yii\caching\Cache|primary cache]] registered with the application.

An application component is created the first time it is accessed through the above expression. Any further accesses will return the same component instance.

Application components can be any objects. You can register them by configuring the [[yii\base\Application::components]] property in application configurations. For example,

[
    'components' => [
        // register "cache" component using a class name
        'cache' => 'yii\caching\ApcCache',

        // register "db" component using a configuration array
        'db' => [
            'class' => 'yii\db\Connection',
            'dsn' => 'mysql:host=localhost;dbname=demo',
            'username' => 'root',
            'password' => '',
        ],

        // register "search" component using an anonymous function
        'search' => function () {
            return new app\components\SolrService;
        },
    ],
]

Info: While you can register as many application components as you want, you should do this judiciously. Application components are like global variables. Using too many application components can potentially make your code harder to test and maintain. In many cases, you can simply create a local component and use it when needed.

Bootstrapping Components

As mentioned above, an application component will only be instantiated when it is being accessed the first time. If it is not accessed at all during a request, it will not be instantiated. Sometimes, however, you may want to instantiate an application component for every request, even if it is not explicitly accessed. To do so, you may list its ID in the [[yii\base\Application::bootstrap|bootstrap]] property of the application.

You can also use Closures to bootstrap customized components. Returning an instantiated component is not required. A Closure can also be used simply for running code after [[yii\base\Application]] instantiation.

For example, the following application configuration makes sure the log component is always loaded:

[
    'bootstrap' => [
        'log',
        function($app){
            return new ComponentX();
        },
        function($app){
            // some code
           return;
        }
    ],
    'components' => [
        'log' => [
            // configuration for "log" component
        ],
    ],
]

Core Application Components

Yii defines a set of core application components with fixed IDs and default configurations. For example, the [[yii\web\Application::request|request]] component is used to collect information about a user request and resolve it into a route; the [[yii\base\Application::db|db]] component represents a database connection through which you can perform database queries. It is with help of these core application components that Yii applications are able to handle user requests.

Below is the list of the predefined core application components. You may configure and customize them like you do with normal application components. When you are configuring a core application component, if you do not specify its class, the default one will be used.

  • [[yii\web\AssetManager|assetManager]]: manages asset bundles and asset publishing. Please refer to the Assets section for more details.
  • [[yii\db\Connection|db]]: represents a database connection through which you can perform DB queries. Note that when you configure this component, you must specify the component class as well as other required component properties, such as [[yii\db\Connection::dsn]]. Please refer to the Database Access Objects section for more details.
  • [[yii\base\Application::errorHandler|errorHandler]]: handles PHP errors and exceptions. Please refer to the Handling Errors section for more details.
  • [[yii\i18n\Formatter|formatter]]: formats data when they are displayed to end users. For example, a number may be displayed with thousand separator, a date may be formatted in long format. Please refer to the Data Formatting section for more details.
  • [[yii\i18n\I18N|i18n]]: supports message translation and formatting. Please refer to the Internationalization section for more details.
  • [[yii\log\Dispatcher|log]]: manages log targets. Please refer to the Logging section for more details.
  • [[yii\swiftmailer\Mailer|mailer]]: supports mail composing and sending. Please refer to the Mailing section for more details.
  • [[yii\base\Application::response|response]]: represents the response being sent to end users. Please refer to the Responses section for more details.
  • [[yii\base\Application::request|request]]: represents the request received from end users. Please refer to the Requests section for more details.
  • [[yii\web\Session|session]]: represents the session information. This component is only available in [[yii\web\Application|Web applications]]. Please refer to the Sessions and Cookies section for more details.
  • [[yii\web\UrlManager|urlManager]]: supports URL parsing and creation. Please refer to the Routing and URL Creation section for more details.
  • [[yii\web\User|user]]: represents the user authentication information. This component is only available in [[yii\web\Application|Web applications]]. Please refer to the Authentication section for more details.
  • [[yii\web\View|view]]: supports view rendering. Please refer to the Views section for more details.

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

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

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

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

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