### Example Object Configuration Source: https://www.yiiframework.com/doc/guide/2.0/ru/concept-configurations Illustrates a concrete example of an object configuration, setting properties, an event handler, and a behavior. ```php [ 'class' => 'app\components\SearchEngine', 'apiKey' => 'xxxxxxxx', 'on search' => function ($event) { Yii::info("Keyword searched: " . $event->keyword); }, 'as indexer' => [ 'class' => 'app\components\IndexerBehavior', // ... начальные значения свойств ... ], ] ``` -------------------------------- ### Install Composer Asset Plugin and Create Yii Project Source: https://www.yiiframework.com/doc/guide/2.0/ru/tutorial-start-from-scratch Installs the Composer asset plugin globally and then creates a new Yii project using the 'mysoft/yii2-app-coolone' template. Ensure you have Composer installed globally. ```bash composer global require "fxp/composer-asset-plugin:^1.4.1" composer create-project --prefer-dist --stability=dev mysoft/yii2-app-coolone new-project ``` -------------------------------- ### Basic Application Configuration Example Source: https://www.yiiframework.com/doc/guide/2.0/ru/concept-configurations Provides an example of a basic application configuration array, including essential components like cache, mailer, log, and database. ```php $config = [ 'id' => 'basic', 'basePath' => dirname(__DIR__), 'extensions' => require __DIR__ . '/../vendor/yiisoft/extensions.php', 'components' => [ 'cache' => [ 'class' => 'yii\caching\FileCache', ], 'mailer' => [ 'class' => 'yii\swiftmailer\Mailer', ], 'log' => [ 'class' => 'yii\log\Dispatcher', 'traceLevel' => YII_DEBUG ? 3 : 0, 'targets' => [ [ 'class' => 'yii\log\FileTarget', ], ], ], 'db' => [ 'class' => 'yii\db\Connection', 'dsn' => 'mysql:host=localhost;dbname=stay2', 'username' => 'root', 'password' => '', 'charset' => 'utf8', ], ], ]; ``` -------------------------------- ### Install Yii Basic Application with Composer Source: https://www.yiiframework.com/doc/guide/2.0/ru/start-installation Use this command to install the latest stable version of Yii into a directory named 'basic'. ```bash composer create-project --prefer-dist yiisoft/yii2-app-basic basic ``` -------------------------------- ### Module Configuration File Example in Yii 2.0 Source: https://www.yiiframework.com/doc/guide/2.0/ru/structure-modules Provides an example of a PHP configuration file for a Yii 2.0 module, similar to application configuration. ```php [ // список конфигураций компонентов ], 'params' => [ // список параметров ], ]; ``` -------------------------------- ### Verify Yii Installation via Browser Source: https://www.yiiframework.com/doc/guide/2.0/ru/start-installation After installation, access this URL in your browser to see the welcome page. Ensure your web server is configured correctly. ```url http://localhost/basic/web/index.php ``` -------------------------------- ### Example composer.json for yiisoft/yii2-imagine Source: https://www.yiiframework.com/doc/guide/2.0/ru/structure-extensions This is a complete example of a `composer.json` file for the `yiisoft/yii2-imagine` extension. It demonstrates package name, type, description, keywords, license, support links, authors, dependencies, and autoloading configuration. ```json { // название пакета "name": "yiisoft/yii2-imagine", // тип пакета "type": "yii2-extension", "description": "The Imagine integration for the Yii framework", "keywords": ["yii2", "imagine", "image", "helper"], "license": "BSD-3-Clause", "support": { "issues": "https://github.com/yiisoft/yii2/issues?labels=ext%3Aimagine", "forum": "https://forum.yiiframework.com/", "wiki": "https://www.yiiframework.com/wiki/", "irc": "ircs://irc.libera.chat:6697/yii", "source": "https://github.com/yiisoft/yii2" }, "authors": [ { "name": "Antonio Ramirez", "email": "amigo.cobos@gmail.com" } ], // зависимости пакета "require": { "yiisoft/yii2": "~2.0.0", "imagine/imagine": "v0.5.0" }, // указание автозагрузчика классов "autoload": { "psr-4": { "yii\\imagine\": "" } } } ``` -------------------------------- ### Formatter Localization Examples Source: https://www.yiiframework.com/doc/guide/2.0/ru/output-formatting Demonstrates how the `locale` property of the formatter affects date output. Ensure the PHP intl extension is installed for full localization. ```php Yii::$app->formatter->locale = 'en-US'; echo Yii::$app->formatter->asDate('2014-01-01'); // выведет: January 1, 2014 Yii::$app->formatter->locale = 'de-DE'; echo Yii::$app->formatter->asDate('2014-01-01'); // выведет: 1. January 2014 Yii::$app->formatter->locale = 'ru-RU'; echo Yii::$app->formatter->asDate('2014-01-01'); // выведет: 1 января 2014 г. ``` -------------------------------- ### Asset Configuration File Example Source: https://www.yiiframework.com/doc/guide/2.0/ru/structure-assets This is an example of the `assets.php` configuration file. It defines JS/CSS compressors, whether to delete source files, the bundles to process, and the target output structure. Note that path aliases like `@webroot` and `@web` are not available in the console environment and must be explicitly defined. ```php 'java -jar compiler.jar --js {from} --js_output_file {to}', // Настроить команду/обратный вызов для сжатия файлов CSS: 'cssCompressor' => 'java -jar yuicompressor.jar --type css {from} -o {to}', // Whether to delete asset source after compression: 'deleteSource' => false, // Список комплектов ресурсов для сжатия: 'bundles' => [ // 'yii\web\YiiAsset', // 'yii\web\JqueryAsset', ], // Комплект ресурса после сжатия: 'targets' => [ 'all' => [ 'class' => 'yii\web\AssetBundle', 'basePath' => '@webroot/assets', 'baseUrl' => '@web/assets', 'js' => 'js/all-{hash}.js', 'css' => 'css/all-{hash}.css', ], ], // Настройка менеджера ресурсов: 'assetManager' => [ ], ]; ``` -------------------------------- ### Install fxp/composer-asset-plugin Globally Source: https://www.yiiframework.com/doc/guide/2.0/ru/structure-assets Install the composer-asset-plugin globally to enable management of Bower and NPM packages within Composer. This command should be run once per machine. ```bash composer global require "fxp/composer-asset-plugin:^1.4.1" ``` -------------------------------- ### Check Docker Installation Source: https://www.yiiframework.com/doc/guide/2.0/ru/tutorial-docker Verify that Docker is installed and running by checking the output of `docker ps`. This command should display information about running containers. ```bash docker ps ``` -------------------------------- ### Install Yii via Composer Source: https://www.yiiframework.com/doc/guide/2.0/ru/tutorial-yii-integration Use this Composer command to install the Yii framework, which is necessary for integrating Yii into third-party systems that use Composer for dependency management. ```bash composer require yiisoft/yii2 ``` -------------------------------- ### Install Composer Dependencies in a New Container Source: https://www.yiiframework.com/doc/guide/2.0/ru/tutorial-docker Run Composer's install command within a temporary container using `docker-compose run --rm php composer install`. The `--rm` flag ensures the container is removed after execution. ```bash docker-compose run --rm php composer install ``` -------------------------------- ### Get Help for Message Configuration Command Source: https://www.yiiframework.com/doc/guide/2.0/ru/tutorial-i18n Execute this command to view available parameters and usage instructions for the `message/config` command. ```bash ./yii help message/config ``` -------------------------------- ### Start Docker Services Source: https://www.yiiframework.com/doc/guide/2.0/ru/tutorial-docker Use `docker-compose up -d` to launch all defined services for your application stack in detached mode (in the background). ```bash docker-compose up -d ``` -------------------------------- ### Get User List (XML) Source: https://www.yiiframework.com/doc/guide/2.0/ru/rest-quick-start Fetch a paginated list of users in XML format by setting the 'Accept' header to 'application/xml'. ```bash $ curl -i -H "Accept:application/xml" "http://localhost/users" HTTP/1.1 200 OK Date: Sun, 02 Mar 2014 05:31:43 GMT Server: Apache/2.2.26 (Unix) DAV/2 PHP/5.4.20 mod_ssl/2.2.26 OpenSSL/0.9.8y X-Powered-By: PHP/5.4.20 X-Pagination-Total-Count: 1000 X-Pagination-Page-Count: 50 X-Pagination-Current-Page: 1 X-Pagination-Per-Page: 20 Link: ; rel=self, ; rel=next, ; rel=last Transfer-Encoding: chunked Content-Type: application/xml 1 ... 2 ... ... ``` -------------------------------- ### Configure Mailer Component Source: https://www.yiiframework.com/doc/guide/2.0/ru/tutorial-mailing Set up the 'mailer' component in your application configuration. This example uses the yii2-swiftmailer extension. ```php return [ //.... 'components' => [ 'mailer' => [ 'class' => 'yii\swiftmailer\Mailer', ], ], ]; ``` -------------------------------- ### Lazy Loading Example Source: https://www.yiiframework.com/doc/guide/2.0/ru/db-active-record Demonstrates lazy loading where SQL queries are executed upon first access to a relation property. ```php // SELECT * FROM `customer` WHERE `id` = 123 $customer = Customer::findOne(123); // SELECT * FROM `order` WHERE `customer_id` = 123 $orders = $customer->orders; // SQL-запрос не выполняется $orders2 = $customer->orders; ``` -------------------------------- ### Filter Conditions in GET Request Source: https://www.yiiframework.com/doc/guide/2.0/ru/rest-filtering-collections Example of filter conditions represented in URL query parameters for a GET request. This format is equivalent to the JSON structure shown for POST requests. ```http ?filter[id][in][]=2&filter[id][in][]=5&filter[id][in][]=9&filter[title][like]=cheese ``` -------------------------------- ### API Versioning with Accept Header Source: https://www.yiiframework.com/doc/guide/2.0/ru/rest-versioning Example of how the Accept header can be used to specify API versioning, either as a parameter or a content type. ```http // как параметр Accept: application/json; version=v1 // как тип содержимого, определенный поставщиком API Accept: application/vnd.company.myapp-v1+json ``` -------------------------------- ### Application Instantiation Source: https://www.yiiframework.com/doc/guide/2.0/ru/concept-configurations Shows how to create and run a Yii web application instance using a configuration array. ```php (new yii\web\Application($config))->run(); ``` -------------------------------- ### Configure yii\rest\UrlRule with 'extraPatterns' Source: https://www.yiiframework.com/doc/guide/2.0/ru/rest-routing Add custom URL patterns to yii\rest\UrlRule using 'extraPatterns'. This example adds a 'GET search' pattern for the 'search' action. ```php [ 'class' => 'yii\rest\UrlRule', 'controller' => 'user', 'extraPatterns' => [ 'GET search' => 'search', ], ] ``` -------------------------------- ### Define FileStorage and DocumentsReader Classes Source: https://www.yiiframework.com/doc/guide/2.0/ru/concept-di-container Defines the FileStorage and DocumentsReader classes, which are used in subsequent container configuration examples. No specific setup is required beyond defining these classes. ```php class FileStorage { public function __construct($root) { // делаем что-то } } class DocumentsReader { public function __construct(FileStorage $fs) { // делаем что-то } } ``` -------------------------------- ### Implement Migration to Create a Table Source: https://www.yiiframework.com/doc/guide/2.0/ru/db-migrations This example shows how to implement the `up()` method to create a 'news' table with an ID, title, and content. The `down()` method is implemented to drop the table. ```php createTable('news', [ 'id' => Schema::TYPE_PK, 'title' => Schema::TYPE_STRING . ' NOT NULL', 'content' => Schema::TYPE_TEXT, ]); } public function down() { $this->dropTable('news'); } } ``` -------------------------------- ### Create Project Directory Source: https://www.yiiframework.com/doc/guide/2.0/ru/tutorial-yii-as-micro-framework Create a directory for your micro-application and navigate into it. These commands are for Unix-like systems. ```bash mkdir micro-app cd micro-app ``` -------------------------------- ### Create Controller Actions in Yii Source: https://www.yiiframework.com/doc/guide/2.0/ru/structure-controllers Define actions as public methods within a controller class. The method name must start with 'action'. The return value of the action method is the response sent to the user. This example shows 'index' and 'hello-world' actions. ```php namespace app\controllers; use yii\web\Controller; class SiteController extends Controller { public function actionIndex() { return $this->render('index'); } public function actionHelloWorld() { return 'Hello World'; } } ``` -------------------------------- ### Module Initialization with Configuration in Yii 2.0 Source: https://www.yiiframework.com/doc/guide/2.0/ru/structure-modules Demonstrates initializing a module using `Yii::configure` with properties loaded from an external configuration file. ```php public function init() { parent::init(); // инициализация модуля с помощью конфигурации, загруженной из config.php \Yii::configure($this, require __DIR__ . '/config.php'); } ``` -------------------------------- ### Automatic Dependency Resolution with Type Hinting Source: https://www.yiiframework.com/doc/guide/2.0/ru/concept-di-container The DI Container automatically resolves dependencies declared via constructor type hints. This example shows how `UserLister` depends on `UserFinderInterface`, which in turn depends on `Connection`. Registering these dependencies allows `get('userLister')` to instantiate `UserLister` with all its resolved dependencies. ```php namespace app\models; use yii\base\BaseObject; use yii\db\Connection; use yii\di\Container; interface UserFinderInterface { function findUser(); } class UserFinder extends BaseObject implements UserFinderInterface { public $db; public function __construct(Connection $db, $config = []) { $this->db = $db; parent::__construct($config); } public function findUser() { } } class UserLister extends BaseObject { public $finder; public function __construct(UserFinderInterface $finder, $config = []) { $this->finder = $finder; parent::__construct($config); } } $container = new Container; $container->set('yii\db\Connection', [ 'dsn' => '...', ]); $container->set('app\models\UserFinderInterface', [ 'class' => 'app\models\UserFinder', ]); $container->set('userLister', 'app\models\UserLister'); $lister = $container->get('userLister'); // which is equivalent to: $db = new \yii\db\Connection(['dsn' => '...']); $finder = new UserFinder($db); $lister = new UserLister($finder); ``` -------------------------------- ### Install Composer on Linux/Mac Source: https://www.yiiframework.com/doc/guide/2.0/ru/start-installation Use this command to install Composer globally on Linux or Mac systems. Ensure you have curl installed. ```bash curl -sS https://getcomposer.org/installer | php mv composer.phar /usr/local/bin/composer ``` -------------------------------- ### Instantiating Custom Component with Parameters and Configuration Source: https://www.yiiframework.com/doc/guide/2.0/ru/concept-components Demonstrates two ways to instantiate a custom component: directly with parameters and a configuration array, or using Yii::createObject() for more advanced dependency injection. ```php $component = new MyClass(1, 2, ['prop1' => 3, 'prop2' => 4]); ``` ```php $component = \Yii::createObject([ 'class' => MyClass::class, 'prop1' => 3, 'prop2' => 4, ], [1, 2]); ``` -------------------------------- ### Install Bash Autocompletion for Yii Source: https://www.yiiframework.com/doc/guide/2.0/ru/tutorial-console This command downloads the Bash autocompletion script for Yii and saves it to the system's completion directory. Ensure Bash completion is installed on your system. After installation, restart your terminal or source ~/.bashrc. ```bash curl -L https://raw.githubusercontent.com/yiisoft/yii2/master/contrib/completion/bash/yii -o /etc/bash_completion.d/yii ``` -------------------------------- ### Start Transaction on Slave Server Source: https://www.yiiframework.com/doc/guide/2.0/ru/db-dao Explicitly start a database transaction on a slave server by accessing the slave connection. ```php $transaction = Yii::$app->db->slave->beginTransaction(); ``` -------------------------------- ### Example Accept Header for JSON Source: https://www.yiiframework.com/doc/guide/2.0/ru/rest-response-formatting This is an example of an Accept header that requests a JSON response with a quality factor of 1.0. ```http Accept: application/json; q=1.0, */*; q=0.1 ``` -------------------------------- ### Advanced Publishing Logic with init() and beforeCopy Source: https://www.yiiframework.com/doc/guide/2.0/ru/structure-assets Implement custom publishing logic by overriding the `init()` method and using the `beforeCopy` callback in `publishOptions`. This example ensures only 'fonts' and 'css' subdirectories are copied. ```php publishOptions['beforeCopy'] = function ($from, $to) { if (basename(dirname($from)) !== 'font-awesome') { return true; } $dirname = basename($from); return $dirname === 'fonts' || $dirname === 'css'; }; } } ``` -------------------------------- ### Install Yii 2 Debug Extension Source: https://www.yiiframework.com/doc/guide/2.0/ru/tool-debugger Install the yiisoft/yii2-debug extension using Composer. This command adds the package to your project and updates dependencies. ```bash php composer.phar require --prefer-dist yiisoft/yii2-debug ``` -------------------------------- ### Load All Fixtures Source: https://www.yiiframework.com/doc/guide/2.0/ru/test-fixtures Use the asterisk wildcard to load all available fixtures. ```bash yii fixture/load "*" ``` ```bash yii "*" ``` -------------------------------- ### Create and Run a Yii Web Application Source: https://www.yiiframework.com/doc/guide/2.0/ru/structure-applications This snippet shows how to include the autoloader and Yii core files, load the application configuration from 'web.php', and then create and run a web application instance. Ensure your configuration file is correctly set up. ```php require __DIR__ . '/../vendor/autoload.php'; require __DIR__ . '/../vendor/yiisoft/yii2/Yii.php'; // загрузка конфигурации приложения $config = require __DIR__ . '/../config/web.php'; // создание объекта приложения и его конфигурирование (new yii\web\Application($config))->run(); ``` -------------------------------- ### Get generated SQL and parameters Source: https://www.yiiframework.com/doc/guide/2.0/ru/db-query-builder Use `createCommand()` to get a `yii\db\Command` object, allowing you to inspect the generated SQL and its bound parameters before execution. ```php $command = (new "\yii\db\Query()") ->select(['id', 'email']) ->from('user') ->where(['last_name' => 'Smith']) ->limit(10) ->createCommand(); // show SQL query echo $command->sql; // show bound parameters print_r($command->params); // returns all rows of the query $rows = $command->queryAll(); ``` -------------------------------- ### Registering Components with Service Locator Source: https://www.yiiframework.com/doc/guide/2.0/ru/concept-service-locator Demonstrates various ways to register components with a Service Locator instance: by class name, configuration array, anonymous function, or an existing object. Ensure necessary classes are imported. ```php use yii\di\ServiceLocator; use yii\caching\FileCache; $locator = new ServiceLocator; // регистрирует "cache", используя имя класса, которое может быть использовано для создания компонента. $locator->set('cache', 'yii\caching\ApcCache'); // регистрирует "db", используя конфигурационный массив, который может быть использован для создания компонента. $locator->set('db', [ 'class' => 'yii\db\Connection', 'dsn' => 'mysql:host=localhost;dbname=demo', 'username' => 'root', 'password' => '', ]); // регистрирует "search", используя анонимную функцию, которая создаёт компонент $locator->set('search', function () { return new app\components\SolrService; }); // регистрирует "pageCache", используя компонент $locator->set('pageCache', new FileCache); ``` -------------------------------- ### API Directory Structure for Versioning Source: https://www.yiiframework.com/doc/guide/2.0/ru/rest-versioning Illustrates a recommended directory structure for organizing API versions using modules. ```plaintext api/ common/ controllers/ UserController.php PostController.php models/ User.php Post.php modules/ v1/ controllers/ UserController.php PostController.php models/ User.php Post.php Module.php v2/ controllers/ UserController.php PostController.php models/ User.php Post.php Module.php ``` -------------------------------- ### Load Fixtures with Global Fixtures Source: https://www.yiiframework.com/doc/guide/2.0/ru/test-fixtures Include global fixtures that should be loaded before other fixtures. The `InitDbFixture` is used by default. ```bash yii fixture User --globalFixtures='some\name\space\Custom' ``` -------------------------------- ### Creating a Basic Site Controller Source: https://www.yiiframework.com/doc/guide/2.0/ru/structure-controllers Shows how to define a basic controller for a web application, extending yii\web\Controller. ```php namespace app\controllers; use yii\web\Controller; class SiteController extends Controller { } ``` -------------------------------- ### Load Configuration from File Source: https://www.yiiframework.com/doc/guide/2.0/ru/concept-configurations Load application configuration by including a configuration file using the `require` statement. This is typically done in the application's entry script. ```php $config = require 'path/to/web.php'; (new yii\web\Application($config))->run(); ``` -------------------------------- ### Example JSON Response from RESTful API Source: https://www.yiiframework.com/doc/guide/2.0/ru/rest-response-formatting This is an example of a JSON response from a RESTful API, including pagination headers and a JSON array of user objects. ```http $ curl -i -H "Accept: application/json; q=1.0, */*; q=0.1" "http://localhost/users" HTTP/1.1 200 OK Date: Sun, 02 Mar 2014 05:31:43 GMT Server: Apache/2.2.26 (Unix) DAV/2 PHP/5.4.20 mod_ssl/2.2.26 OpenSSL/0.9.8y X-Powered-By: PHP/5.4.20 X-Pagination-Total-Count: 1000 X-Pagination-Page-Count: 50 X-Pagination-Current-Page: 1 X-Pagination-Per-Page: 20 Link: ; rel=self, ; rel=next, ; rel=last Transfer-Encoding: chunked Content-Type: application/json; charset=UTF-8 [ { "id": 1, ... }, { "id": 2, ... }, ... ] ``` -------------------------------- ### Define Application Configuration Source: https://www.yiiframework.com/doc/guide/2.0/ru/concept-configurations Organize complex application configurations into separate PHP files. Each configuration file should return a PHP array representing the configuration. This example shows a basic `web.php` configuration. ```php return [ 'id' => 'basic', 'basePath' => dirname(__DIR__), 'extensions' => require __DIR__ . '/../vendor/yiisoft/extensions.php', 'components' => require __DIR__ . '/components.php', ]; ``` -------------------------------- ### Get Base URL - Yii Url Helper Source: https://www.yiiframework.com/doc/guide/2.0/ru/helper-url Use Url::base() to get the base URL of the current request. The parameter works the same as in Url::home(). ```php $relativeBaseUrl = Url::base(); $absoluteBaseUrl = Url::base(true); $httpsAbsoluteBaseUrl = Url::base('https'); ``` -------------------------------- ### Create and Apply Database Migration Source: https://www.yiiframework.com/doc/guide/2.0/ru/tutorial-yii-as-micro-framework Use these console commands to create a new database migration for the 'posts' table and apply it. Ensure your application configuration is specified. ```bash vendor/bin/yii migrate/create --appconfig=config.php create_post_table --fields="title:string,body:text" ``` ```bash vendor/bin/yii migrate/up --appconfig=config.php ``` -------------------------------- ### Using Cache Component as an Array Source: https://www.yiiframework.com/doc/guide/2.0/ru/caching-data Demonstrates how to use the cache component like an array for setting and getting values. This is equivalent to using the set() and get() methods. ```php $cache['var1'] = $value1; // эквивалентно: $cache->set('var1', $value1); $value2 = $cache['var2']; // эквивалентно: $value2 = $cache->get('var2'); ``` -------------------------------- ### Application Configuration with Dependency Injection Container Source: https://www.yiiframework.com/doc/guide/2.0/ru/concept-configurations Demonstrates configuring the dependency injection container within the application configuration, specifically for widget definitions. ```php $config = [ 'id' => 'basic', 'basePath' => dirname(__DIR__), 'extensions' => require __DIR__ . '/../vendor/yiisoft/extensions.php', 'container' => [ 'definitions' => [ 'yii\widgets\LinkPager' => ['maxButtonCount' => 5] ], 'singletons' => [ // Конфигурация для единожды создающихся объектов ] ] ]; ``` -------------------------------- ### Local Codeception Installation for Yii 2 Source: https://www.yiiframework.com/doc/guide/2.0/ru/test-environment-setup Install Codeception and its extensions locally for a specific Yii 2 project using Composer. This ensures project-specific dependency management. ```bash composer require "codeception/codeception=2.1.*" composer require "codeception/specify=*" composer require "codeception/verify=*" ``` -------------------------------- ### Create Basic Post Table Migration Source: https://www.yiiframework.com/doc/guide/2.0/ru/db-migrations Use this command to generate a basic migration file for creating a 'post' table. The generated migration includes `up` and `down` methods for table creation and dropping. ```bash yii migrate/create create_post_table ``` -------------------------------- ### Configuring Multiple Components via 'components' Property Source: https://www.yiiframework.com/doc/guide/2.0/ru/concept-service-locator Illustrates configuring multiple components for a Service Locator (like the application instance) using the `components` property in a configuration array. This method allows for centralized setup of various services. ```php return [ // ... 'components' => [ 'db' => [ 'class' => 'yii\db\Connection', 'dsn' => 'mysql:host=localhost;dbname=demo', 'username' => 'root', 'password' => '', ], 'cache' => 'yii\caching\ApcCache', 'tz' => function() { return new \DateTimeZone(Yii::$app->formatter->defaultTimeZone); }, 'search' => function () { $solr = new app\components\SolrService('127.0.0.1'); // ... дополнительная инициализация ... return $solr; }, ], ]; ``` -------------------------------- ### Install Yii Unstable Version with Composer Source: https://www.yiiframework.com/doc/guide/2.0/ru/start-installation To install the latest unstable revision of Yii, use the '--stability=dev' option. Avoid using unstable versions on production servers. ```bash composer create-project --prefer-dist --stability=dev yiisoft/yii2-app-basic basic ``` -------------------------------- ### Get Home URL - Yii Url Helper Source: https://www.yiiframework.com/doc/guide/2.0/ru/helper-url Use Url::home() to get the home URL. Pass `true` for an absolute URL or specify a protocol like 'https'. ```php $relativeHomeUrl = Url::home(); $absoluteHomeUrl = Url::home(true); $httpsAbsoluteHomeUrl = Url::home('https'); ``` -------------------------------- ### Configure Asset Installer Paths in composer.json Source: https://www.yiiframework.com/doc/guide/2.0/ru/structure-assets Specify the directories where Bower and NPM packages will be installed by adding these lines to your project's composer.json file. This ensures assets are placed in predictable locations. ```json "extra": { "asset-installer-paths": { "npm-asset-library": "vendor/npm", "bower-asset-library": "vendor/bower" } } ``` -------------------------------- ### Configure Container with Singletons Source: https://www.yiiframework.com/doc/guide/2.0/ru/concept-di-container Configures the container using setSingletons for stateless classes like FileStorage, and setDefinitions for others. This optimizes performance by ensuring single instances of specific dependencies are reused. ```php $container->setSingletons([ 'tempFileStorage' => [ ['class' => 'app\storage\FileStorage'], ['/var/tempfiles'] ], ]); $container->setDefinitions([ 'app\storage\DocumentsReader' => [ ['class' => 'app\storage\DocumentsReader'], [Instance::of('tempFileStorage')] ], 'app\storage\DocumentsWriter' => [ ['class' => 'app\storage\DocumentsWriter'], [Instance::of('tempFileStorage')] ] ]); $reader = $container->get('app\storage\DocumentsReader'); ``` -------------------------------- ### Yii Database Connection DSN Examples Source: https://www.yiiframework.com/doc/guide/2.0/ru/db-dao Examples of Data Source Names (DSN) for various database systems. The DSN format is specific to each database type and is required when configuring a database connection. ```text mysql:host=localhost;dbname=mydatabase ``` ```text sqlite:/path/to/database/file ``` ```text pgsql:host=localhost;port=5432;dbname=mydatabase ``` ```text cubrid:dbname=demodb;host=localhost;port=33000 ``` ```text sqlsrv:Server=localhost;Database=mydatabase ``` ```text dblib:host=localhost;dbname=mydatabase ``` ```text mssql:host=localhost;dbname=mydatabase ``` ```text oci:dbname=//localhost:1521/mydatabase ``` -------------------------------- ### Running Migrate Controller Action in Yii Source: https://www.yiiframework.com/doc/guide/2.0/ru/tutorial-console Example of executing the 'up' action of the MigrateController with specific options. Remember to quote '*' if used to avoid shell expansion. ```bash yii migrate/up 5 --migrationTable=migrations ``` -------------------------------- ### Accessing GET and POST Parameters in Yii 2.0 Source: https://www.yiiframework.com/doc/guide/2.0/ru/runtime-requests Retrieve GET and POST parameters using the `request` application component. This approach is recommended over direct access to `$_GET` and `$_POST` for improved testability. ```php $request = Yii::$app->request; $get = $request->get(); // эквивалентно: $get = $_GET; $id = $request->get('id'); // эквивалентно: $id = isset($_GET['id']) ? $_GET['id'] : null; $id = $request->get('id', 1); // эквивалентно: $id = isset($_GET['id']) ? $_GET['id'] : 1; $post = $request->post(); // эквивалентно: $post = $_POST; $name = $request->post('name'); // эквивалентно: $name = isset($_POST['name']) ? $_POST['name'] : null; $name = $request->post('name', ''); // эквивалентно: $name = isset($_POST['name']) ? $_POST['name'] : ''; ``` -------------------------------- ### Verify Yii Installation via Console Source: https://www.yiiframework.com/doc/guide/2.0/ru/start-installation Navigate to the application directory and run this command to check Yii requirements. This is an alternative to browser verification. ```bash cd basic php requirements.php ``` -------------------------------- ### Load a Fixture Source: https://www.yiiframework.com/doc/guide/2.0/ru/test-fixtures Use this command to load a specific fixture. The `load` action is default for the `fixture` command. ```bash yii fixture/load ``` ```bash yii fixture User ``` ```bash yii fixture/load User ``` -------------------------------- ### Global Codeception Installation for Yii 2 Source: https://www.yiiframework.com/doc/guide/2.0/ru/test-environment-setup Install Codeception and its extensions globally for use across multiple projects on your development machine. This requires adding the Composer global vendor bin directory to your PATH. ```bash composer global require "codeception/codeception=2.1.*" composer global require "codeception/specify=*" composer global require "codeception/verify=*" ``` -------------------------------- ### Configure Alias for Manually Installed Extension Source: https://www.yiiframework.com/doc/guide/2.0/ru/structure-extensions If an extension is installed manually and lacks a class autoloader but follows PSR-4, define an alias in your application's configuration to map the namespace to the extension's directory. ```php [ 'aliases' => [ '@myext' => '@vendor/mycompany/myext', ], ] ``` -------------------------------- ### In Rule Validation Example Source: https://www.yiiframework.com/doc/guide/2.0/ru/input-validation This is a simplified example of using the 'in' validation rule, which is a common way to validate attribute values against a predefined range. It's often used as an alternative to custom validators for simple checks. ```php [ ['status', 'in', 'range' => Status::find()->select('id')->asArray()->column()] ] ```