Skip to content

Commit

Permalink
Merge branch '13064-asset-packagist-docs'
Browse files Browse the repository at this point in the history
  • Loading branch information
SilverFire committed Jun 17, 2017
2 parents 858e801 + 9a18748 commit ded61a1
Show file tree
Hide file tree
Showing 7 changed files with 185 additions and 60 deletions.
10 changes: 3 additions & 7 deletions docs/guide-ru/start-installation.md
Original file line number Diff line number Diff line change
Expand Up @@ -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, можете использовать следующую команду,
Expand Down
77 changes: 73 additions & 4 deletions docs/guide-ru/structure-assets.md
Original file line number Diff line number Diff line change
Expand Up @@ -138,13 +138,82 @@ class FontAwesomeAsset extends AssetBundle

В выше указанном примере определён комплект ресурсов для [пакета "fontawesome"](http://fontawesome.io/). Задан параметр публикации `beforeCopy`, здесь только `fonts` и `css` поддиректории будут опубликованы.

### Bower и NPM Ресурсы<span id="bower-npm-assets"></span>
### Установка ресурсов Bower и NPM<span id="bower-npm-assets"></span>

Большинство 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 пакет в директорию, соответствующую этим псевдонимам.

Expand Down
12 changes: 8 additions & 4 deletions docs/guide-ru/tutorial-yii-integration.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 и даны решения проблем, которые могут возникнуть при установке.
Expand Down
13 changes: 5 additions & 8 deletions docs/guide/start-installation.md
Original file line number Diff line number Diff line change
Expand Up @@ -55,21 +55,18 @@ by running `composer self-update`.
### Installing Yii <span id="installing-from-composer"></span>

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.
Expand Down
80 changes: 75 additions & 5 deletions docs/guide/structure-assets.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 <span id="bower-npm-assets"></span>
### Bower and NPM Assets installation <span id="bower-npm-assets"></span>

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.

Expand Down
22 changes: 13 additions & 9 deletions docs/guide/tutorial-start-from-scratch.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,34 +22,38 @@ The first step is to clone the basic Yii template's Git repository:
git clone [email protected]: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
------

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
```
Loading

0 comments on commit ded61a1

Please sign in to comment.