yakoffka.ru
    грабли, костыли и велосипеды php, css, html, js и прочего

    Yii 2.0 часть 4. Advanced - расширенный шаблон приложения

    YiiОбзор расширенного шаблона Advanced. Yii 2.0. конспект-памятка курса 'Полное руководство по Yii 2.0' с незначительными вариациями. Оригинал на русском языке можно найти здесь.

    АЛАРМА!!! Данная памятка являет собой откровенный копипаст! Для ознакомления с первоисточником перейдите по ссылке, указанной выше.

    копипастил Капустин Яков

    оглавление

    Расширенный шаблон отличается от основного в первую очередь разделением на пользовательскую и административную части. Его установка с помощью composer мало чем отличается от установки basic-шаблона:

    composer create-project --prefer-dist yiisoft/yii2-app-advanced a1
    bash:
    yo@yo-Lenovo-G510:/var/www/html/yii$ composer create-project --prefer-dist yiisoft/yii2-app-advanced a1 Installing yiisoft/yii2-app-advanced (2.0.14) - Installing yiisoft/yii2-app-advanced (2.0.14): Loading from cache Created project in a1 Loading composer repositories with package information Updating dependencies (including require-dev) Package operations: 65 installs, 0 updates, 0 removals - Installing yiisoft/yii2-composer (2.0.7): Loading from cache - Installing doctrine/lexer (v1.0.1): Loading from cache - Installing egulias/email-validator (2.1.7): Loading from cache - Installing swiftmailer/swiftmailer (v6.1.3): Loading from cache - Installing bower-asset/jquery (3.2.1): Loading from cache - Installing bower-asset/yii2-pjax (2.0.7.1): Loading from cache - Installing bower-asset/punycode (v1.3.2): Loading from cache - Installing cebe/markdown (1.1.2): Loading from cache - Installing ezyang/htmlpurifier (v4.10.0): Loading from cache - Installing bower-asset/inputmask (3.3.11): Loading from cache - Installing yiisoft/yii2 (2.0.15.1): Loading from cache - Installing yiisoft/yii2-swiftmailer (2.1.2): Loading from cache - Installing bower-asset/bootstrap (v3.3.7): Loading from cache - Installing yiisoft/yii2-bootstrap (2.0.8): Loading from cache - Installing yiisoft/yii2-debug (2.0.14): Loading from cache - Installing bower-asset/typeahead.js (v0.11.1): Loading from cache - Installing phpspec/php-diff (v1.1.0): Loading from cache - Installing yiisoft/yii2-gii (2.0.8): Loading from cache - Installing fzaninotto/faker (v1.8.0): Loading from cache - Installing yiisoft/yii2-faker (2.0.4): Loading from cache - Installing symfony/polyfill-ctype (v1.10.0): Loading from cache - Installing symfony/yaml (v4.2.2): Loading from cache - Installing symfony/finder (v4.2.2): Loading from cache - Installing symfony/contracts (v1.0.2): Loading from cache - Installing symfony/event-dispatcher (v4.2.2): Loading from cache - Installing symfony/polyfill-mbstring (v1.10.0): Loading from cache - Installing symfony/dom-crawler (v4.2.2): Loading from cache - Installing symfony/css-selector (v4.2.2): Loading from cache - Installing symfony/console (v4.2.2): Loading from cache - Installing symfony/browser-kit (v4.2.2): Loading from cache - Installing ralouphie/getallheaders (2.0.5): Loading from cache - Installing psr/http-message (1.0.1): Loading from cache - Installing guzzlehttp/psr7 (1.5.2): Loading from cache - Installing sebastian/version (2.0.1): Loading from cache - Installing sebastian/resource-operations (2.0.1): Loading from cache - Installing sebastian/recursion-context (3.0.0): Loading from cache - Installing sebastian/object-reflector (1.1.1): Loading from cache - Installing sebastian/object-enumerator (3.0.3): Loading from cache - Installing sebastian/global-state (2.0.0): Loading from cache - Installing sebastian/exporter (3.1.0): Loading from cache - Installing sebastian/environment (4.0.1): Loading from cache - Installing sebastian/diff (3.0.1): Loading from cache - Installing sebastian/comparator (3.0.2): Loading from cache - Installing phpunit/php-timer (2.0.0): Loading from cache - Installing phpunit/php-text-template (1.2.1): Loading from cache - Installing phpunit/php-file-iterator (2.0.2): Loading from cache - Installing theseer/tokenizer (1.1.0): Loading from cache - Installing sebastian/code-unit-reverse-lookup (1.0.1): Loading from cache - Installing phpunit/php-token-stream (3.0.1): Loading from cache - Installing phpunit/php-code-coverage (6.1.4): Loading from cache - Installing doctrine/instantiator (1.1.0): Loading from cache - Installing webmozart/assert (1.4.0): Loading from cache - Installing phpdocumentor/reflection-common (1.0.1): Loading from cache - Installing phpdocumentor/type-resolver (0.4.0): Loading from cache - Installing phpdocumentor/reflection-docblock (4.3.0): Loading from cache - Installing phpspec/prophecy (1.8.0): Loading from cache - Installing phar-io/version (2.0.1): Loading from cache - Installing phar-io/manifest (1.0.3): Loading from cache - Installing myclabs/deep-copy (1.8.1): Loading from cache - Installing phpunit/phpunit (7.5.2): Loading from cache - Installing codeception/stub (2.0.4): Loading from cache - Installing codeception/phpunit-wrapper (7.6.1): Loading from cache - Installing behat/gherkin (v4.6.0): Loading from cache - Installing codeception/base (2.4.5): Loading from cache - Installing codeception/verify (0.3.3): Loading from cache egulias/email-validator suggests installing ext-intl (PHP Internationalization Libraries are required to use the SpoofChecking validation) swiftmailer/swiftmailer suggests installing ext-intl (Needed to support internationalized email addresses) swiftmailer/swiftmailer suggests installing true/punycode (Needed to support internationalized email addresses, if ext-intl is not installed) symfony/contracts suggests installing psr/cache (When using the Cache contracts) symfony/contracts suggests installing psr/container (When using the Service contracts) symfony/contracts suggests installing symfony/cache-contracts-implementation symfony/contracts suggests installing symfony/service-contracts-implementation symfony/contracts suggests installing symfony/translation-contracts-implementation symfony/event-dispatcher suggests installing symfony/dependency-injection symfony/event-dispatcher suggests installing symfony/http-kernel symfony/console suggests installing psr/log-implementation (For using the console logger) symfony/console suggests installing symfony/lock symfony/console suggests installing symfony/process symfony/browser-kit suggests installing symfony/process sebastian/global-state suggests installing ext-uopz (*) phpunit/php-code-coverage suggests installing ext-xdebug (^2.6.0) phpunit/phpunit suggests installing phpunit/php-invoker (^2.0) phpunit/phpunit suggests installing ext-xdebug (*) codeception/base suggests installing aws/aws-sdk-php (For using AWS Auth in REST module and Queue module) codeception/base suggests installing codeception/phpbuiltinserver (Start and stop PHP built-in web server for your tests) codeception/base suggests installing codeception/specify (BDD-style code blocks) codeception/base suggests installing flow/jsonpath (For using JSONPath in REST module) codeception/base suggests installing league/factory-muffin (For DataFactory module) codeception/base suggests installing league/factory-muffin-faker (For Faker support in DataFactory module) codeception/base suggests installing phpseclib/phpseclib (for SFTP option in FTP Module) codeception/base suggests installing stecman/symfony-console-completion (For BASH autocompletion) codeception/base suggests installing symfony/phpunit-bridge (For phpunit-bridge support) Writing lock file Generating autoload files yo@yo-Lenovo-G510:/var/www/html/yii$

    Затем необходимо перейти в директорию приложения и произвести его инициализацию:

    yo@yo-Lenovo-G510:/var/www/html/yii$ cd a1/
    yo@yo-Lenovo-G510:/var/www/html/yii/a1$ ./init
    bash:
    yo@yo-Lenovo-G510:/var/www/html/yii$ cd a1/ yo@yo-Lenovo-G510:/var/www/html/yii/a1$ ./init Yii Application Initialization Tool v1.0 Which environment do you want the application to be initialized in? [0] Development [1] Production Your choice [0-1, or "q" to quit] 0 Initialize the application under 'Development' environment? [yes|no] yes Start initialization ... generate common/config/params-local.php generate common/config/test-local.php generate common/config/main-local.php generate yii_test.bat generate console/config/params-local.php generate console/config/main-local.php generate yii_test generate yii generate frontend/web/robots.txt generate frontend/web/index.php generate frontend/web/index-test.php generate frontend/config/params-local.php generate frontend/config/test-local.php generate frontend/config/main-local.php generate backend/web/robots.txt generate backend/web/index.php generate backend/web/index-test.php generate backend/config/params-local.php generate backend/config/test-local.php generate backend/config/main-local.php generate cookie validation key in backend/config/main-local.php generate cookie validation key in frontend/config/main-local.php chmod 0777 backend/runtime chmod 0777 backend/web/assets chmod 0777 frontend/runtime chmod 0777 frontend/web/assets chmod 0755 yii chmod 0755 yii_test ... initialization completed. yo@yo-Lenovo-G510:/var/www/html/yii/a1$

    Создаём базу данных:

    yo@yo-Lenovo-G510:/var/www/html/yii/a1$ mysql -u root -p
    mysql> create database yii2_a1;
    bash:
    yo@yo-Lenovo-G510:/var/www/html/yii/a1$ mysql -u root -p Enter password: Welcome to the MySQL monitor. Commands end with ; or \g. Your MySQL connection id is 52 Server version: 5.7.25-0ubuntu0.16.04.2 (Ubuntu) Copyright (c) 2000, 2019, Oracle and/or its affiliates. All rights reserved. Oracle is a registered trademark of Oracle Corporation and/or its affiliates. Other names may be trademarks of their respective owners. Type 'help;' or '\h' for help. Type '\c' to clear the current input statement. mysql> create database yii2_a1; Query OK, 1 row affected (0,00 sec) mysql> exit Bye yo@yo-Lenovo-G510:/var/www/html/yii/a1$

    После выполнения необходимых настроек базы данных (dsn, username, password) в common/config/main-local.php и запускаю миграцию:

    yo@yo-Lenovo-G510:/var/www/html/yii/a1$ ./yii migrate
    bash:
    yo@yo-Lenovo-G510:/var/www/html/yii/a1$ ./yii migrate Yii Migration Tool (based on Yii v2.0.15.1) Creating migration history table "migration"...Done. Total 1 new migration to be applied: m130524_201442_init Apply the above migration? (yes|no) [no]:yes *** applying m130524_201442_init > create table {{%user}} ... done (time: 0.061s) *** applied m130524_201442_init (time: 0.078s) 1 migration was applied. Migrated up successfully. yo@yo-Lenovo-G510:/var/www/html/yii/a1$

    На данном этапе можно запустить встроенный веб-сервер для frontend/web и backend/web:

    yo@yo-Lenovo-G510:/var/www/html/yii/a1$ php -S localhost:8021 -t frontend/web
    yo@yo-Lenovo-G510:/var/www/html/yii/a1$ php -S localhost:8022 -t backend/web

    Я не буду выполнять данные команды, так как использую установленный веб сервер. Также не лишним будет запуск скрипта requirements.php, находящегося в коревой директории. Он запустит проверку выполнения системных требований приложения и выведет результат на экран:

    yo@yo-Lenovo-G510:/var/www/html/yii/a1$ php requirements.php
    bash:
    yo@yo-Lenovo-G510:/var/www/html/yii/a1$ php requirements.php yo@yo-Lenovo-G510:/var/www/html/yii/a1$ Yii Application Requirement Checker This script checks if your server configuration meets the requirements for running Yii application. It checks if the server is running the right version of PHP, if appropriate PHP extensions have been loaded, and if php.ini file settings are correct. Check conclusion: ----------------- PHP version: OK Reflection extension: OK PCRE extension: OK SPL extension: OK Ctype extension: OK MBString extension: OK OpenSSL extension: OK Intl extension: WARNING!!! Required by: Internationalization support Memo: PHP Intl extension 1.0.2 or higher is required when you want to use advanced parameters formatting in Yii::t(), non-latin languages with Inflector::slug(), IDN-feature of EmailValidator or UrlValidator or the yii\i18n\Formatter class. ICU version: WARNING!!! Required by: Internationalization support Memo: ICU 49.0 or higher is required when you want to use # placeholder in plural rules (for example, plural in Formatter::asRelativeTime()) in the yii\i18n\Formatter class. Your current ICU version is (ICU is missing). ICU Data version: WARNING!!! Required by: Internationalization support Memo: ICU Data 49.1 or higher is required when you want to use # placeholder in plural rules (for example, plural in Formatter::asRelativeTime()) in the yii\i18n\Formatter class. Your current ICU Data version is (ICU Data is missing). Fileinfo extension: OK DOM extension: OK IPv6 support: OK PDO extension: OK PDO SQLite extension: OK PDO MySQL extension: OK PDO PostgreSQL extension: WARNING!!! Required by: All DB-related classes Memo: Required for PostgreSQL database. Memcache extension: WARNING!!! Required by: MemCache APC extension: WARNING!!! Required by: ApcCache GD PHP extension with FreeType support: OK ImageMagick PHP extension with PNG support: WARNING!!! Required by: Captcha Memo: Either GD PHP extension with FreeType support or ImageMagick PHP extension with PNG support is required for image CAPTCHA. Expose PHP: WARNING!!! Required by: Security reasons Memo: "expose_php" should be disabled at php.ini PHP allow url include: OK PHP mail SMTP: OK ------------------------------------------ Errors: 0 Warnings: 8 Total checks: 24 yo@yo-Lenovo-G510:/var/www/html/yii/a1$