Commit 343e1596 by Antonio Ramirez

add concept-autoloading.md -wip

parent 0d9bc8b2
Autocarga de clases
===================
Yii depende del [mecanismo de autocarga de clases](http://www.php.net/manual/en/language.oop5.autoload.php) para localizar
e incluir los archivos de las clases requiridas. Proporciona un cargador de clases de alto rendimiento que cumple con el
[estandard PSR-4](https://github.com/php-fig/fig-standards/blob/master/proposed/psr-4-autoloader/psr-4-autoloader.md).
El cargador se instala cuando incluyes el archivo `Yii.php`.
> Nota: Para simplificar la descripción, en esta sección sólo hablaremos de la carga automática de clases. Sin embargo,
ten en cuenta que el contenido que describimos aquí también se aplica a la autocarga de interfaces y rasgos (Traits).
Usando el Autocargador de Yii <a name="using-yii-autoloader"></a>
-----------------------------
Para utilizar el el autocargador de clases de Yii, deberías seguir dos reglas básicas cuando desarrolles y nombres tus
clases:
* Cada clase debe estar bajo un espacio de nombre (namespace). Por ejemplo `foo\bar\MyClass`.
* Cada clase debe estar guardada en un archivo individual cuya ruta está determinada por el siguiente algoritmo:
```php
// $className es un nombre completo de clase con las iniciales barras invertidas.
$classFile = Yii::getAlias('@' . str_replace('\\', '/', $className) . '.php');
```
For example, if a class name is `foo\bar\MyClass`, the [alias](concept-aliases.md) for the corresponding class file path
would be `@foo/bar/MyClass.php`. In order for this alias to be able to be resolved into a file path,
either `@foo` or `@foo/bar` must be a [root alias](concept-aliases.md#defining-aliases).
When you are using the [Basic Application Template](start-basic.md), you may put your classes under the top-level
namespace `app` so that they can be autoloaded by Yii without the need of defining a new alias. This is because
`@app` is a [predefined alias](concept-aliases.md#predefined-aliases), and a class name like `app\components\MyClass`
can be resolved into the class file `AppBasePath/components/MyClass.php`, according to the algorithm we just described.
In the [Advanced Application Template](tutorial-advanced-app.md), each tier has its own root alias. For example,
the front-end tier has a root alias `@frontend` while the back-end tier `@backend`. As a result, you may
put the front-end classes under the namespace `frontend` while the back-end classes under `backend`. This will
allow these classes to be autoloaded by the Yii autoloader.
Class Map <a name="class-map"></a>
---------
The Yii class autoloader supports the *class map* feature which maps class names to the corresponding class file paths.
When the autoloader is loading a class, it will first check if the class is found in the map. If so, the corresponding
file path will be included directly without further check. This makes class autoloading super fast. In fact,
all core Yii classes are being autoloaded this way.
You may add a class to the class map `Yii::$classMap` as follows,
```php
Yii::$classMap['foo\bar\MyClass'] = 'path/to/MyClass.php';
```
[Aliases](concept-aliases.md) can be used to specify class file paths. You should set the class map in the
[bootstrapping](runtime-bootstrapping.md) process so that the map is ready before your classes are used.
Using Other Autoloaders <a name="using-other-autoloaders"></a>
-----------------------
Because Yii embraces Composer as a package dependency manager, it is recommended that you also install
the Composer autoloader. If you are using some 3rd-party libraries that have their autoloaders, you should
also install them.
When you are using the Yii autoloader together with other autoloaders, you should include the `Yii.php` file
*after* all other autoloaders are installed. This will make the Yii autoloader to be the first one responding to
any class autoloading request. For example, the following code is extracted from
the [entry script](structure-entry-scripts.md) of the [Basic Application Template](start-basic.md). The first
line installs the Composer autoloader, while the second line installs the Yii autoloader.
```php
require(__DIR__ . '/../vendor/autoload.php');
require(__DIR__ . '/../vendor/yiisoft/yii2/Yii.php');
```
You may use the Composer autoloader alone without the Yii autoloader. However, by doing so, the performance
of your class autoloading may be degraded, and you must follow the rules set by Composer in order for your classes
to be autoloadable.
> Info: If you do not want to use the Yii autoloader, you must create your own version of the `Yii.php` file
and include it in your [entry script](structure-entry-scripts.md).
Autoloading Extension Classes <a name="autoloading-extension-classes"></a>
-----------------------------
The Yii autoloader is capable of autoloading [extension](structure-extensions.md) classes. The sole requirement
is that an extension specifies the `autoload` section correctly in its `composer.json` file. Please refer to the
[Composer documentation](https://getcomposer.org/doc/04-schema.md#autoload) for more details about specifying `autoload`.
In case you do not use the Yii autoloader, the Composer autoloader can still autoload extension classes for you.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment