From 9a18748e1f68fd51fa08c2c99bffa190281d144d Mon Sep 17 00:00:00 2001 From: SilverFire - Dmitry Naumenko Date: Fri, 21 Apr 2017 11:33:17 +0300 Subject: [PATCH] Documented possibility of using asset-packagist --- docs/guide-ru/start-installation.md | 10 +-- docs/guide-ru/structure-assets.md | 77 ++++++++++++++++++++-- docs/guide-ru/tutorial-yii-integration.md | 12 ++-- docs/guide/start-installation.md | 13 ++-- docs/guide/structure-assets.md | 80 +++++++++++++++++++++-- docs/guide/tutorial-start-from-scratch.md | 22 ++++--- docs/guide/tutorial-yii-integration.md | 31 +++------ 7 files changed, 185 insertions(+), 60 deletions(-) diff --git a/docs/guide-ru/start-installation.md b/docs/guide-ru/start-installation.md index 5d818ecc953..78c79750d99 100644 --- a/docs/guide-ru/start-installation.md +++ b/docs/guide-ru/start-installation.md @@ -47,18 +47,14 @@ mv composer.phar /usr/local/bin/composer ### Установка Yii ```bash -composer global require "fxp/composer-asset-plugin:^1.3.1" composer create-project --prefer-dist yiisoft/yii2-app-basic basic ``` -Первая команда устанавливает [composer asset plugin](https://github.com/francoispluchino/composer-asset-plugin/), -который позволяет управлять зависимостями пакетов bower и npm через Composer. Эту команду достаточно выполнить один раз. -Вторая команда устанавливает последнюю стабильную версию Yii в директорию `basic`. Если хотите, можете выбрать другое +Эта команда команда устанавливает последнюю стабильную версию Yii в директорию `basic`. Если хотите, можете выбрать другое имя директории. -> Info: Если команда `composer create-project` не выполняется нормально, убедитесь, что вы корректно установили composer -> asset plugin. Вы можете сделать это выполнив `composer global show`. Вывод должен содержать `fxp/composer-asset-plugin`. -> Также можно обратиться к [разделу "Troubleshooting" документации Composer](https://getcomposer.org/doc/articles/troubleshooting.md). +> Info: Если команда `composer create-project` не выполняется нормально, попробуйте обратиться к +> [разделу "Troubleshooting" документации Composer](https://getcomposer.org/doc/articles/troubleshooting.md). > Там описаны другие типичные ошибки. После того, как вы исправили ошибку, запустите `composer update` в директории `basic`. > Tip: Если вы хотите установить последнюю нестабильную ревизию Yii, можете использовать следующую команду, diff --git a/docs/guide-ru/structure-assets.md b/docs/guide-ru/structure-assets.md index 76ee5cead5a..a407d959f1a 100644 --- a/docs/guide-ru/structure-assets.md +++ b/docs/guide-ru/structure-assets.md @@ -138,13 +138,82 @@ class FontAwesomeAsset extends AssetBundle В выше указанном примере определён комплект ресурсов для [пакета "fontawesome"](http://fontawesome.io/). Задан параметр публикации `beforeCopy`, здесь только `fonts` и `css` поддиректории будут опубликованы. -### Bower и NPM Ресурсы +### Установка ресурсов Bower и NPM Большинство JavaScript/CSS пакетов управляются [Bower](http://bower.io/) и/или [NPM](https://www.npmjs.org/). -Если Вашим приложением или расширением используется такой пакет, то рекомендуется следовать следующим этапам для управления ресурсами библиотеки: +В мире PHP мы испольуем Composer для управления зависимостями, но он не позволяет устанавливать пакеты Bower и NPM, просто указывая их в `composer.json`. -1. Исправить файл `composer.json` Вашего приложения или расширения и включить пакет в список в раздел `require`. Следует использовать `bower-asset/PackageName` (для Bower пакетов) или `npm-asset/PackageName` (для NPM пакетов) для обращения к соответствующей библиотеке. -2. Создать класс комплекта ресурсов и перечислить JavaScript/CSS файлы, которые Вы планируете использовать в Вашем приложении или расширении. Вы должны задать свойство [[yii\web\AssetBundle::sourcePath|sourcePath]] как `@bower/PackageName` или `@npm/PackageName`. +Чтобы получить такую возможность, нужно немного настроить Composer. Существует два варианта: + +_____ + +##### Используя репозиторий asset-packagist + +Этот способ удовлетворяет потребности большинства проектов, которым нужны Bower или NPM пакеты. + +> Note: Начиная с версии 2.0.13, Basic и Advanced шаблоны приложений уже сконфигурированы для использования asset-packagist, + так что этот раздел можно пропустить. + +В файле `composer.json` вашего проекта, добавьте следующие строки: + +```json +"repositories": [ + { + "type": "composer", + "url": "https://asset-packagist.org" + } +] +``` + +Настройте [алиасы](concept-aliases.md) `@npm` и `@bower` в файле [конфигурации вашего приложения](concept-configurations.md): + +```php +$config = [ + ... + 'aliases' => [ + '@bower' => '@vendor/bower-asset', + '@npm' => '@vendor/npm-asset', + ], + ... +]; +``` + +Посетите [asset-packagist.org](https://asset-packagist.org) чтобы узнать, как это работает. + +##### Используя fxp/composer-asset-plugin + +По сравнению с asset-packagist, composer-asset-plugin не требует изменять конфигурацию приложения. Вместо этого, требуется +установить специальный глобальный пакет Composer, выполнив следующую команду: + +```bash +composer global require "fxp/composer-asset-plugin:^1.3.1" +``` + +Эта команда устанавливает [composer asset plugin](https://github.com/francoispluchino/composer-asset-plugin/) глобально, +что позволит устанавливать зависимости из Bower и NPM. После установки все проекты на вашем комьютере будут поддерживать +установку Bower и NPM пакетов, описанных в `composer.json`. + +Добавьте следующие строки в `composer.json` вашего проекта, чтобы указать директории, в которые будут установлены +необходимые Bower и NPM пакеты: + +```json +"extra": { + "asset-installer-paths": { + "npm-asset-library": "vendor/npm", + "bower-asset-library": "vendor/bower" + } +} +``` + +> Note: `fxp/composer-asset-plugin` выполняет команду `composer update` существенно дольше, по сравнению с asset-packagist. + +____ + +После настройки Composer для поддержки Bower и NPM пакетов: + +1. Исправьте файл `composer.json` Вашего приложения или расширения и включите пакет в список в раздел `require`. Следует использовать `bower-asset/PackageName` (для Bower пакетов) или `npm-asset/PackageName` (для NPM пакетов) для обращения к соответствующей библиотеке. +2. Выполните `composer update` +3. Создайте класс комплекта ресурсов и перечислите JavaScript/CSS файлы, которые Вы планируете использовать в Вашем приложении или расширении. Вы должны задать свойство [[yii\web\AssetBundle::sourcePath|sourcePath]] как `@bower/PackageName` или `@npm/PackageName`. Это происходит потому, что Composer устанавливает Bower или NPM пакет в директорию, соответствующую этим псевдонимам. diff --git a/docs/guide-ru/tutorial-yii-integration.md b/docs/guide-ru/tutorial-yii-integration.md index 3d1a1c775f4..3000912ca0c 100644 --- a/docs/guide-ru/tutorial-yii-integration.md +++ b/docs/guide-ru/tutorial-yii-integration.md @@ -61,11 +61,15 @@ Yii::$classMap['Class2'] = 'path/to/Class2.php'; Поскольку в Yii реализована масса полезных функций, они могут пригодиться при разработке или расширении сторонних систем, таких как WordPress и Joomla, или приложений, разработанных с помощью других PHP-фреймворков. Например, в сторонней системе можно задействовать класс [[yii\helpers\ArrayHelper]] или использовать функционал [Active Record](db-active-record.md). Для этого обычно нужно сделать две вещи: установить Yii и подключить Yii. -Если сторонняя система использует для управления зависимостями Composer, Yii можно просто установить с помощью следующих команд: +Если сторонняя система использует для управления зависимостями Composer, Yii можно просто установить с помощью следующей команды: - composer global require "fxp/composer-asset-plugin:^1.3.1" - composer require yiisoft/yii2 - composer install +```bash +composer require yiisoft/yii2 +``` + +Если вам интересны возможности Yii, например, по работе с базами данных, но вы не планируете использование +[ресурсов](structure-assets.md), вы можете установить специальный пакет, который предотвращает загрузку Bower и NPM +пакетов. Смотрите [cebe/assetfree-yii2](https://github.com/cebe/assetfree-yii2) для деталей. Первая команда устанавливает [composer asset plugin](https://github.com/francoispluchino/composer-asset-plugin/), который позволяет управлять зависимостями пакетов bower и npm через Composer. Даже если вы хотите воспользоваться слоем абстракции баз данных или другими элементами Yii, не связанными с ресурсами, этот плагин все равно придется установить, так как без него не установится пакет Yii. В разделе [об установке Yii](start-installation.md#installing-via-composer) более подробно описана работа с Composer и даны решения проблем, которые могут возникнуть при установке. diff --git a/docs/guide/start-installation.md b/docs/guide/start-installation.md index c36df4d87dc..9e5bd16004d 100644 --- a/docs/guide/start-installation.md +++ b/docs/guide/start-installation.md @@ -55,21 +55,18 @@ by running `composer self-update`. ### Installing Yii -With Composer installed, you can install Yii by running the following commands under a Web-accessible folder: +With Composer installed, you can install Yii application template by running the following command +under a Web-accessible folder: ```bash -composer global require "fxp/composer-asset-plugin:^1.3.1" composer create-project --prefer-dist yiisoft/yii2-app-basic basic ``` -The first command installs the [composer asset plugin](https://github.com/francoispluchino/composer-asset-plugin/) -which allows managing bower and npm package dependencies through Composer. You only need to run this command -once for all. The second command installs the latest stable version of Yii in a directory named `basic`. +This will install the latest stable version of Yii application template in a directory named `basic`. You can choose a different directory name if you want. -> Info: If the `composer create-project` command fails make sure you have the composer asset plugin installed correctly. -> You can do that by running `composer global show`, which should contain an entry `fxp/composer-asset-plugin`. -> You may also refer to the [Troubleshooting section of the Composer Documentation](https://getcomposer.org/doc/articles/troubleshooting.md) +> Info: If the `composer create-project` command fails you may also refer to the +> [Troubleshooting section of the Composer Documentation](https://getcomposer.org/doc/articles/troubleshooting.md) > for common errors. When you have fixed the error, you can resume the aborted installation > by running `composer update` inside of the `basic` directory. diff --git a/docs/guide/structure-assets.md b/docs/guide/structure-assets.md index 2ad0ea157b4..d979a5fbe59 100644 --- a/docs/guide/structure-assets.md +++ b/docs/guide/structure-assets.md @@ -203,16 +203,86 @@ The above example defines an asset bundle for the ["fontawesome" package](http:/ the `only` publishing option, only the `fonts` and `css` subdirectories will be published. -### Bower and NPM Assets +### Bower and NPM Assets installation -Most JavaScript/CSS packages are managed by [Bower](http://bower.io/) and/or [NPM](https://www.npmjs.org/). -If your application or extension is using such a package, it is recommended that you follow these steps to manage -the assets in the library: +Most JavaScript/CSS packages are managed by [Bower](http://bower.io/) and/or [NPM](https://www.npmjs.org/) package +managers. In PHP world we have Composer, that manages PHP dependencies, but it is possible to load +both Bower and NPM packages using `composer.json` just as PHP packages. + +To achieve this, we should configure our composer a bit. There are two options to do that: + +___ + +##### Using asset-packagist repository + +This way will satisfy requirements of the majority of projects, that need NPM or Bower packages. + +> Note: Since 2.0.13 both Basic and Advanced application templates are pre-configured to use asset-packagist + by default, so you can skip this section. + +In the `composer.json` of your project, add the following lines: + +```json +"repositories": [ + { + "type": "composer", + "url": "https://asset-packagist.org" + } +] +``` + +Adjust `@npm` and `@bower` [aliases](concept-aliases.md) in you [application configuration](concept-configurations.md): + +```php +$config = [ + ... + 'aliases' => [ + '@bower' => '@vendor/bower-asset', + '@npm' => '@vendor/npm-asset', + ], + ... +]; +``` + +Visit [asset-packagist.org](https://asset-packagist.org) to know, how it works. + +##### Using fxp/composer-asset-plugin + +Comparing to to using asset-packagist, composer-asset-plugin does not require to change application config. Instead, it +requires to install a special Composer plugin globally by running the following command: + +```bash +composer global require "fxp/composer-asset-plugin:^1.3.1" +``` + +This command installs [composer asset plugin](https://github.com/francoispluchino/composer-asset-plugin/) globally +which allows managing Bower and NPM package dependencies through Composer. After the plugin installation, +every single project on your computer will support Bower and NPM packages through `composer.json`. + +Add the following lines to `composer.json` of your project to adjust directories where the installed packages +will be placed, if you want to publish them using Yii: + +```json +"extra": { + "asset-installer-paths": { + "npm-asset-library": "vendor/npm", + "bower-asset-library": "vendor/bower" + } +} +``` + +> Note: `fxp/composer-asset-plugin` significantly slows down the `composer update` command in comparison + to asset-packagist. + +____ + +After configuring Composer to support Bower and NPM: 1. Modify the `composer.json` file of your application or extension and list the package in the `require` entry. You should use `bower-asset/PackageName` (for Bower packages) or `npm-asset/PackageName` (for NPM packages) to refer to the library. -2. Create an asset bundle class and list the JavaScript/CSS files that you plan to use in your application or extension. +2. Run `composer update` +3. Create an asset bundle class and list the JavaScript/CSS files that you plan to use in your application or extension. You should specify the [[yii\web\AssetBundle::sourcePath|sourcePath]] property as `@bower/PackageName` or `@npm/PackageName`. This is because Composer will install the Bower or NPM package in the directory corresponding to this alias. diff --git a/docs/guide/tutorial-start-from-scratch.md b/docs/guide/tutorial-start-from-scratch.md index a56383425d6..9249331e290 100644 --- a/docs/guide/tutorial-start-from-scratch.md +++ b/docs/guide/tutorial-start-from-scratch.md @@ -22,27 +22,32 @@ The first step is to clone the basic Yii template's Git repository: git clone git@github.com:yiisoft/yii2-app-basic.git ``` -Then wait for the repository to be downloaded to your computer. Since the changes made to the template won't be pushed back, you can delete the `.git` directory and all -of its contents from the download. +Then wait for the repository to be downloaded to your computer. Since the changes made to the template won't be pushed +back, you can delete the `.git` directory and all of its contents from the download. Modify the Files ------------ -Next, you'll want to modify the `composer.json` to reflect your template. Change the `name`, `description`, `keywords`, `homepage`, `license`, and `support` values -to describe your new template. Also adjust the `require`, `require-dev`, `suggest`, and other options to match your template's requirements. +Next, you'll want to modify the `composer.json` to reflect your template. Change the `name`, `description`, `keywords`, +`homepage`, `license`, and `support` values to describe your new template. Also adjust the `require`, `require-dev`, +`suggest`, and other options to match your template's requirements. > Note: In the `composer.json` file, use the `writable` parameter under `extra` to specify > per file permissions to be set after an application is created using the template. -Next, actually modify the structure and contents of the application as you would like the default to be. Finally, update the README file to be applicable to your template. +Next, actually modify the structure and contents of the application as you would like the default to be. +Finally, update the README file to be applicable to your template. Make a Package -------------- -With the template defined, create a Git repository from it, and push your files there. If you're going to open source your template, [Github](http://github.com) is the best place to host it. If you intend to keep your template non-collaborative, any Git repository site will do. +With the template defined, create a Git repository from it, and push your files there. If you're going to open source +your template, [Github](http://github.com) is the best place to host it. If you intend to keep your template +non-collaborative, any Git repository site will do. -Next, you need to register your package for Composer's sake. For public templates, the package should be registered at [Packagist](https://packagist.org/). -For private templates, it is a bit more tricky to register the package. For instructions, see the [Composer documentation](https://getcomposer.org/doc/05-repositories.md#hosting-your-own). +Next, you need to register your package for Composer's sake. For public templates, the package should be registered +at [Packagist](https://packagist.org/). For private templates, it is a bit more tricky to register the package. For +instructions, see the [Composer documentation](https://getcomposer.org/doc/05-repositories.md#hosting-your-own). Use the Template ------ @@ -50,6 +55,5 @@ Use the Template That's all that's required to create a new Yii project template. Now you can create projects using your template: ``` -composer global require "fxp/composer-asset-plugin:^1.3.1" composer create-project --prefer-dist --stability=dev mysoft/yii2-app-coolone new-project ``` diff --git a/docs/guide/tutorial-yii-integration.md b/docs/guide/tutorial-yii-integration.md index 4c418fd5018..86fa743cb21 100644 --- a/docs/guide/tutorial-yii-integration.md +++ b/docs/guide/tutorial-yii-integration.md @@ -79,32 +79,17 @@ frameworks. For example, you may want to use the [[yii\helpers\ArrayHelper]] cla [Active Record](db-active-record.md) feature in a third-party system. To achieve this goal, you mainly need to take two steps: install Yii, and bootstrap Yii. -If the third-party system uses Composer to manage its dependencies, you can simply run the following commands -to install Yii: +If the third-party system uses Composer to manage its dependencies, run the following command to add Yii +to the project requirements: - composer global require "fxp/composer-asset-plugin:^1.3.1" - composer require yiisoft/yii2 - composer install - -The first command installs the [composer asset plugin](https://github.com/francoispluchino/composer-asset-plugin/) -which allows managing bower and npm package dependencies through Composer. Even if you only want to use the database -layer or other non-asset related features of Yii, this is required to install the Yii composer package. - -If you want to use the [Asset publishing feature of Yii](structure-assets.md) you should also add the following configuration -to the `extra` section in your `composer.json`: - -```json -{ - ... - "extra": { - "asset-installer-paths": { - "npm-asset-library": "vendor/npm", - "bower-asset-library": "vendor/bower" - } - } -} +```bash +composer require yiisoft/yii2 ``` +In case you would like to use only the database abstraction layer or other non-asset related features of Yii, +you should require a special composer package that prevent Bower and NPM packages installation. See +[cebe/assetfree-yii2](https://github.com/cebe/assetfree-yii2) for details. + See also the general [section about installing Yii](start-installation.md#installing-via-composer) for more information on Composer and solution to possible issues popping up during the installation.