东方孤思子(Paris·QianSen)
10 years ago
65 changed files with 2086 additions and 590 deletions
@ -0,0 +1,356 @@
|
||||
Comportamientos |
||||
=============== |
||||
|
||||
Comportamientos son instancias de [[yii\base\Behavior]] o sus clases "hija". Comportamientos, también conocido como |
||||
[mixins](http://en.wikipedia.org/wiki/Mixin), te permiten mejorar la funcionalidad de un [[yii\base\Component|componente]] |
||||
existente sin necesidad de modificar su herencia de clases. |
||||
Cuando un comportamiento se une a un componente, "inyectará" sus métodos y propiedades dentro del componente, y podrás |
||||
acceder a esos métodos y propiedades como si hubieran estado definidos por la clase de componente. Además, un |
||||
comportamiento puede responder a [eventos](concept-events.md) disparados por el componente de modo que se pueda personalizar |
||||
o adaptar a la ejecución normal del código del componente. |
||||
|
||||
|
||||
Usando comportamientos <a name="using-behaviors"></a> |
||||
---------------------- |
||||
|
||||
Para poder utilizar un comportamiento, primero tienes que unirlo a un [[yii\base\Component|componente]]. Describiremos cómo |
||||
puedes vincular un comportamiento en la próxima sub-sección. |
||||
|
||||
Una vez que el comportamiento ha sido vinculado a un componente, su uso es sencillo. |
||||
|
||||
Puedes usar a una variable *pública* o a una [propiedad](concept-properties.md) definida por un `getter` y/o un `setter` |
||||
del comportamiento a través del componente con el que se ha vinculado, como por ejemplo, |
||||
|
||||
```php |
||||
// "prop1" es una propiedad definida en la clase comportamiento |
||||
echo $component->prop1; |
||||
$component->prop1 = $value; |
||||
``` |
||||
|
||||
También puedes llamar métodos *públicos* del comportamiento de una forma similar, |
||||
|
||||
```php |
||||
// bar() es un método público definido dentro de la clase comportamiento |
||||
$component->bar(); |
||||
``` |
||||
|
||||
Como puedes ver, aunque `$component` no tiene definida `prop1` y `bar()`, pueden ser usadas como si fueran parte |
||||
definida del componente. |
||||
|
||||
Si dos comportamientos definen la misma propiedad o método y ambos están vinculados con el mismo componente, el |
||||
comportamiento que ha sido vinculado primero tendrá preferencia cuando se esté accediendo a la propiedad o método. |
||||
|
||||
Un comportamiento puede estar asociado con un nombre cuando se une a un componente. Si este es el caso, es posible |
||||
acceder al objeto de comportamiento mediante el nombre, como se muestra a continuación, |
||||
|
||||
```php |
||||
$behavior = $component->getBehavior('myBehavior'); |
||||
``` |
||||
|
||||
También puedes acceder a todos los comportamientos vinculados al componente: |
||||
|
||||
```php |
||||
$behaviors = $component->getBehaviors(); |
||||
``` |
||||
|
||||
|
||||
Vinculando Comportamientos <a name="attaching-behaviors"></a> |
||||
-------------------------- |
||||
|
||||
Puedes vincular un comportamiento a un [[yii\base\Component|componente]] ya sea estática o dinámicamente. La primera forma |
||||
es la más comúnmente utilizada en la práctica. |
||||
|
||||
Para unir un comportamiento estáticamente, reemplaza el método [[yii\base\Component::behaviors()|behaviors()]] de la |
||||
clase componente que se está conectando. Por ejemplo, |
||||
|
||||
```php |
||||
namespace app\models; |
||||
|
||||
use yii\db\ActiveRecord; |
||||
use app\components\MyBehavior; |
||||
|
||||
class User extends ActiveRecord |
||||
{ |
||||
public function behaviors() |
||||
{ |
||||
return [ |
||||
// comportamiento anónimo, sólo el nombre de la clase del comportamiento |
||||
MyBehavior::className(), |
||||
|
||||
// comportamiento nombrado, sólo el nombre de la clase del comportamiento |
||||
'myBehavior2' => MyBehavior::className(), |
||||
|
||||
// comportamiento anónimo, matriz de configuración |
||||
[ |
||||
'class' => MyBehavior::className(), |
||||
'prop1' => 'value1', |
||||
'prop2' => 'value2', |
||||
], |
||||
|
||||
// comportamiento nombrado, matriz de configuración |
||||
'myBehavior4' => [ |
||||
'class' => MyBehavior::className(), |
||||
'prop1' => 'value1', |
||||
'prop2' => 'value2', |
||||
] |
||||
]; |
||||
} |
||||
} |
||||
``` |
||||
|
||||
El método [[yii\base\Component::behaviors()|behaviors()]] tiene que devolver la lista de los comportamientos |
||||
[configuraciones](concept-configurations.md). |
||||
Cada configuración de un comportamiento puede ser el nombre de la clase o una matriz de configuración. |
||||
|
||||
Puedes asociciar un nombre a un comportamiento especificándolo en la clave de la matriz correspondiente a la configuración |
||||
del comportamiento. En este caso, el comportamiento puede ser llamado un *comportamiento nombrado* (named behavior). En |
||||
el ejemplo anterior, hay dos tipos de comportamientos nombrados: `myBehavior2` y `myBehavior4`. Si un comportamiento |
||||
no está asociado con un nombre, se le llama *comportamiento anónimo* (anonymous behavior). |
||||
|
||||
Para vincular un comportamiento dinámicamente, llama al método [[yii\base\Component::attachBehavior()]] desde el componente al |
||||
que se le va a unir el comportamiento. Por ejemplo, |
||||
|
||||
```php |
||||
use app\components\MyBehavior; |
||||
|
||||
// vincular un objeto comportamiento "behavior" |
||||
$component->attachBehavior('myBehavior1', new MyBehavior); |
||||
|
||||
// vincular una clase comportamiento |
||||
$component->attachBehavior('myBehavior2', MyBehavior::className()); |
||||
|
||||
// asociar una matriz de configuración |
||||
$component->attachBehavior('myBehavior3', [ |
||||
'class' => MyBehavior::className(), |
||||
'prop1' => 'value1', |
||||
'prop2' => 'value2', |
||||
]); |
||||
``` |
||||
|
||||
You may attach multiple behaviors at once by using the [[yii\base\Component::attachBehaviors()]] method. |
||||
For example, |
||||
|
||||
```php |
||||
$component->attachBehaviors([ |
||||
'myBehavior1' => new MyBehavior, // a named behavior |
||||
MyBehavior::className(), // an anonymous behavior |
||||
]); |
||||
``` |
||||
|
||||
También puedes asociar comportamientos a traves de [configuraciones](concept-configurations.md) compor el siguiente |
||||
ejemplo. Para más detalles, por favor visita la sección [Configuraciones](concept-configurations.md#configuration-format). |
||||
|
||||
```php |
||||
[ |
||||
'as myBehavior2' => MyBehavior::className(), |
||||
|
||||
'as myBehavior3' => [ |
||||
'class' => MyBehavior::className(), |
||||
'prop1' => 'value1', |
||||
'prop2' => 'value2', |
||||
], |
||||
] |
||||
``` |
||||
|
||||
|
||||
Desasociar Comportamientos <a name="detaching-behaviors"></a> |
||||
-------------------------- |
||||
|
||||
Para desasociar un comportamiento, puedes llamar el método [[yii\base\Component::detachBehavior()]] con el nombre con el |
||||
que se le asoció: |
||||
|
||||
```php |
||||
$component->detachBehavior('myBehavior1'); |
||||
``` |
||||
|
||||
También puedes desvincular *todos* los comportamientos: |
||||
|
||||
```php |
||||
$component->detachBehaviors(); |
||||
``` |
||||
|
||||
|
||||
Definiendo Comportamientos <a name="defining-behaviors"></a> |
||||
-------------------------- |
||||
|
||||
Para definir un comportamiento, crea una clase extendendiéndola de [[yii\base\Behavior]] o una de sus clases "hija". Por ejemplo, |
||||
|
||||
```php |
||||
namespace app\components; |
||||
|
||||
use yii\base\Model; |
||||
use yii\base\Behavior; |
||||
|
||||
class MyBehavior extends Behavior |
||||
{ |
||||
public $prop1; |
||||
|
||||
private $_prop2; |
||||
|
||||
public function getProp2() |
||||
{ |
||||
return $this->_prop2; |
||||
} |
||||
|
||||
public function setProp2($value) |
||||
{ |
||||
$this->_prop2 = $value; |
||||
} |
||||
|
||||
public function foo() |
||||
{ |
||||
// ... |
||||
} |
||||
} |
||||
``` |
||||
|
||||
El código anterior define la clase del comportamiento `app\components\MyBehavior` que provee dos propiedades `prop1` y |
||||
`prop2`, y un método `foo()` al componente con el que está asociado. |
||||
|
||||
The above code defines the behavior class `app\components\MyBehavior` which will provide two properties |
||||
`prop1` and `prop2`, and one method `foo()` to the component it is attached to. Fíjese que la propiedad `prop2` esta |
||||
definida a través del getter `getProp2()` y el setter `setProp2()`. Esto es debido a que [[yii\base\Object]] es una |
||||
clase "ancestro" (o padre) de [[yii\base\Behavior]], la cual soporta la definición de [propiedades](concept-properties.md) por |
||||
getters/setters. |
||||
|
||||
En un comportamiento, puedes acceder al componente al que está vinculado a través de la propiedad [[yii\base\Behavior::owner]]. |
||||
|
||||
Si un omportamiento necesita responder a los eventos que han sido disparados desde el componente al qu están asociados, |
||||
debería sobreescribir el método [[yii\base\Behavior::events()]]. Por ejemplo, |
||||
|
||||
```php |
||||
namespace app\components; |
||||
|
||||
use yii\db\ActiveRecord; |
||||
use yii\base\Behavior; |
||||
|
||||
class MyBehavior extends Behavior |
||||
{ |
||||
// ... |
||||
|
||||
public function events() |
||||
{ |
||||
return [ |
||||
ActiveRecord::EVENT_BEFORE_VALIDATE => 'beforeValidate', |
||||
]; |
||||
} |
||||
|
||||
public function beforeValidate($event) |
||||
{ |
||||
// ... |
||||
} |
||||
} |
||||
``` |
||||
|
||||
El método [[yii\base\Behavior::events()|events()]] tiene que devolver un listado de eventos y sus correspondientes |
||||
controladores (handlers). El código anterior declara el evento [[yii\db\ActiveRecord::EVENT_BEFORE_VALIDATE|EVENT_BEFORE_VALIDATE]] |
||||
con su controlador `beforeValidate()`. Cuando se especifica un controlador de evento, pudes utilizar uno de los siguientes |
||||
formatos: |
||||
|
||||
* una cadena que se refiere al nombre de un método de la clase comportamiento, como el ejemplo anterior; |
||||
* una matriz con un objeto o nombre de la clase, y el nombre de un método, por ejemplo, `[$object, 'nombreMétodo']`; |
||||
* una función anónima. |
||||
|
||||
El formato de un controlador de eventos tendría que ser como se describe a continuación, donde `$event` se refiere al |
||||
parámetro `evento`. Por favor, visita la sección [Eventos](concept-events.md) para obtener más información acerca de |
||||
eventos. |
||||
|
||||
```php |
||||
function ($event) { |
||||
} |
||||
``` |
||||
|
||||
|
||||
Utilizando `TimestampBehavior` <a name="using-timestamp-behavior"></a> |
||||
----------------------------- |
||||
|
||||
Para terminar, vamos a echar un vistazo a [[yii\behaviors\TimestampBehavior]] - un comportamiento que soporta de forma |
||||
automática la actualización de atributos `timestamp` (sellos de tiempo) de un [[yii\db\ActiveRecord|Registro Activo]] |
||||
(Active Record) cuando éste está siendo guardado. |
||||
|
||||
Primero, vincula este comportamiento a la clase [[yii\db\ActiveRecord|Active Record]] que desees utilizar. |
||||
|
||||
```php |
||||
namespace app\models\User; |
||||
|
||||
use yii\db\ActiveRecord; |
||||
use yii\behaviors\TimestampBehavior; |
||||
|
||||
class User extends ActiveRecord |
||||
{ |
||||
// ... |
||||
|
||||
public function behaviors() |
||||
{ |
||||
return [ |
||||
[ |
||||
'class' => TimestampBehavior::className(), |
||||
'attributes' => [ |
||||
ActiveRecord::EVENT_BEFORE_INSERT => ['created_at', 'updated_at'], |
||||
ActiveRecord::EVENT_BEFORE_UPDATE => ['updated_at'], |
||||
], |
||||
], |
||||
]; |
||||
} |
||||
} |
||||
``` |
||||
|
||||
La configuración del comportamiento anterior especifica que |
||||
|
||||
* cuando el registro está siendo insertado, el comportamiento debe asignar el sello de tiempo actual a los atributos |
||||
`created_at` y `updated_at`; |
||||
* cuando el registro está siendo actualizado, el comportamiento debe asignar el sello de tiempo actual al atributo |
||||
`updated_at. |
||||
|
||||
Ahora si tienes un objeto `User` e intentas guardarlo, descubrirás que sus campos `created_at` y `updated_at` están |
||||
automáticamente actualizados con el sello de tiempo actual: |
||||
|
||||
```php |
||||
$user = new User; |
||||
$user->email = 'test@example.com'; |
||||
$user->save(); |
||||
echo $user->created_at; // muestra el sello tiempo actual (timestamp) |
||||
``` |
||||
|
||||
El comportamiento [[yii\behaviors\TimestampBehavior|TimestampBehavior]] también ofrece un método muy útil llamado |
||||
[[yii\behaviors\TimestampBehavior::touch()|touch()]], que asigna el sello de tiempo actual a un atributo especificado y |
||||
lo guarda automáticamente en la base de datos: |
||||
|
||||
```php |
||||
$user->touch('login_time'); |
||||
``` |
||||
|
||||
|
||||
Comparación con Traits <a name="comparison-with-traits"></a> |
||||
---------------------- |
||||
|
||||
Mientras que los comportamientos son similares a [traits](http://www.php.net/traits) en cuanto que ambos "inyectan" sus |
||||
métodos y propiedades a la clase primaria, son diferentes en muchos aspectos. Tal y como se describe abajo, los dos |
||||
tienen sus ventajas y desventajas. Son much mejor descritos como complementos y no como reemplazos entre sí. |
||||
|
||||
|
||||
### Las Ventajas de los Comportamientos <a name="pros-for-behaviors"></a> |
||||
|
||||
Las clases de comportamientos (Behaviors), como todas las clases, soportan herencias. Traits, por otro lado, pueden ser |
||||
considerados como un copia-y-pega de PHP. Los Traits no soportan la herencia de clases. |
||||
|
||||
Los comportamientos pueden ser asociados y desasociados a un componente dinámicamente sin necesidad de que la clase del |
||||
componente sea modificada. Para usar un trait, debes modificar la clase que la usa. |
||||
|
||||
Los comportamientos son configurables mientras que los traits no. |
||||
|
||||
Los comportamientos pueden personalizar la ejecución de un componente al responder a sus eventos. |
||||
|
||||
Cuando hay un conflicto de nombre entre los diferentes comportamientos vinculados a un mismo componente, el conflicto es |
||||
automáticamente resuelto respetando al que ha sido asociado primero. |
||||
El conflicto de nombres en traits requiere que manualmente sean resueltos cambiando el nombre de las propiedades o métodos |
||||
afectados. |
||||
|
||||
|
||||
### Las Ventajas de los Traits <a name="pros-for-traits"></a> |
||||
|
||||
Los Traits son mucho más eficientes que los comportamientos debido a que los últimos son objetos que consumen tiempo y |
||||
memoria. |
||||
|
||||
Los IDEs (Programas de desarrollo) trabajan mucho mejor con traits ya que forman parte del lenguaje PHP. |
||||
|
@ -0,0 +1,100 @@
|
||||
Componentes |
||||
=========== |
||||
|
||||
Los componentes son los principales bloques de construcción de las aplicaciones Yii. Los componentes son instancias de |
||||
[[yii\base\Component]] o de una clase extendida. Las tres características principales que los componentes proporcionan |
||||
a las otras clases son: |
||||
|
||||
* [Propiedades](concept-properties.md) |
||||
* [Eventos](concept-events.md) |
||||
* [Comportamientos](concept-behaviors.md) |
||||
|
||||
Por separado y combinadas, estas características hacen que las clases Yii sean mucho mas personalizables y sean mucho |
||||
más fáciles de usar. Por ejemplo, el incluido [[yii\jui\DatePicker|widget de selección de fecha]], un componente de la |
||||
interfaz de usuario, puede ser utilizado en una [vista](structure-view.md) para generar un selector de fechas interactivo: |
||||
|
||||
```php |
||||
use yii\jui\DatePicker; |
||||
|
||||
echo DatePicker::widget([ |
||||
'language' => 'ru', |
||||
'name' => 'country', |
||||
'clientOptions' => [ |
||||
'dateFormat' => 'yy-mm-dd', |
||||
], |
||||
]); |
||||
``` |
||||
|
||||
Las propiedades del widget son facilmente modificables porque la clase se extiende de [[yii\base\Component]]. |
||||
|
||||
Mientras que los componentes son muy potentes, son un poco más pesados que los objetos normales, debido al hecho de que |
||||
necesitan más memoria y tiempo de CPU para poder soportar [eventos](concept-events.md) y [comportamientos](concept-behaviors.md) en particular. |
||||
Si tus componentes no necesitan estas dos características, deberías considerar extender tu componente directamente de |
||||
[[yii\base\Object]] en vez de [[yii\base\Component]]. De esta manera harás que tus componentes sean mucho más eficientes que |
||||
que objetos PHP normales, pero con el añadido soporte para [propiedades](concept-properties.md). |
||||
|
||||
Cuando extiendes tu clase de [[yii\base\Component]] o [[yii\base\Object]], se recomienda que sigas las siguientes |
||||
convenciones: |
||||
|
||||
- Si sobrescribes el constructor, especifica un parámetro `$config` como el *último* parámetro del constructor, y después |
||||
pasa este parámetro al constructor de la clase "padre". |
||||
- Siempre llama al constructor del "padre" al *final* de su propio constructor. |
||||
- Si sobrescribes el método [[yii\base\Object::init()]], asegúrate de que llamas a la implementación de la clase "padre" |
||||
*al principio* de tu método `init`. |
||||
|
||||
Por ejemplo: |
||||
|
||||
```php |
||||
namespace yii\components\MyClass; |
||||
|
||||
use yii\base\Object; |
||||
|
||||
class MyClass extends Object |
||||
{ |
||||
public $prop1; |
||||
public $prop2; |
||||
|
||||
public function __construct($param1, $param2, $config = []) |
||||
{ |
||||
// ... inicialización antes de la configuración está siendo aplicada |
||||
|
||||
parent::__construct($config); |
||||
} |
||||
|
||||
public function init() |
||||
{ |
||||
parent::init(); |
||||
|
||||
// ... inicialización despues de la configuración esta siendo aplicada |
||||
} |
||||
} |
||||
``` |
||||
|
||||
Siguiendo esas directrices hará que tus componentes sean [configurables](concept-configurations.md) cuando son creados. Por ejemplo: |
||||
|
||||
```php |
||||
$component = new MyClass(1, 2, ['prop1' => 3, 'prop2' => 4]); |
||||
// alternativamente |
||||
$component = \Yii::createObject([ |
||||
'class' => MyClass::className(), |
||||
'prop1' => 3, |
||||
'prop2' => 4, |
||||
], [1, 2]); |
||||
``` |
||||
|
||||
> Información: Mientras que el enfoque de llamar [[Yii::createObject()]] parece mucho más complicado, es mucho más potente |
||||
debido al hecho de que se implementa en la parte superior de un [contenedor de inyección de dependencia](concept-di-container.md). |
||||
|
||||
|
||||
La clase [[yii\base\Object]] hace cumplir el siguiente ciclo de vida del objeto: |
||||
|
||||
1. Pre-inicialización en el constructor. Puedes establecer los valores predeterminados de propiedades aquí. |
||||
2. Configuración del objeto a través de `$config`. La configuración puede sobrescribir los valores prdeterminados dentro |
||||
del constructor. |
||||
3. Post-inicialización dentro de [[yii\base\Object::init()|init()]]. Puedes sobrescribir este método para realizar |
||||
comprobaciones de validez y normalización de las propiedades. |
||||
4. LLamadas a métodos del objeto. |
||||
|
||||
|
||||
Los tres primeros pasos ocurren dentro del constructor del objeto. Esto significa que una vez obtengas la instancia de |
||||
un objeto, ésta ha sido inicializada para que puedas utilizarla adecuadamente. |
@ -0,0 +1,90 @@
|
||||
Service Locator |
||||
=============== |
||||
|
||||
Service Locator является объектом, который знает, как обеспечить всевозможные службы (или компоненты), которые могут понадобиться в приложении. |
||||
В пределах Service Locator'а, каждый компонент имеет только один экземпляр, который уникально определяется с помощью идентификатора (ID). |
||||
Уникальный идентификатор (ID) может быть использован для извлечения компонента из Service Locator'а. |
||||
|
||||
В Yii Service Locator является экземпляром класса [[yii\di\ServiceLocator]] или его дочернего класса. |
||||
|
||||
Наиболее часто используемый Service Locator в Yii - это объект *приложения*, который можно получить через |
||||
`\Yii::$app`. Обеспечиваемые им службы называют *компонентами приложения*, такие, как компоненты `запрос`, `ответ`, `UrlManager`. |
||||
Вы легко можете настроить эти компоненты или даже заменить их собственными реализациями, |
||||
благодаря функциональным службам, предоставляемым Service Locator'ом. |
||||
|
||||
Помимо объекта приложения, объект каждого модуля так же является Service Locator'ом. |
||||
|
||||
Для использования Service Locator'а первым шагом является регистрация компонентов. |
||||
Компонент может быть зарегистрирован с помощью [[yii\di\ServiceLocator::set()]]. |
||||
Следующий код демонстрирует различные способы регистрации компонентов: |
||||
|
||||
```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); |
||||
``` |
||||
|
||||
После того, как компонент зарегистрирован, вы можете получить к нему доступ, используя уникальный идентификатор (ID), |
||||
одним из двух следующих способов: |
||||
|
||||
```php |
||||
$cache = $locator->get('cache'); |
||||
// или альтернативный |
||||
$cache = $locator->cache; |
||||
``` |
||||
|
||||
Как видно выше, [[yii\di\ServiceLocator]] позволяет обратиться к компоненту, как к свойству, |
||||
при помощи идентификатора (ID) компонента. |
||||
При обращении к компоненту впервые, [[yii\di\ServiceLocator]] будет использовать информацию о регистрации компонента, |
||||
что бы создать новый экземпляр компонента и вернёт его. |
||||
В дальнейшем при обращении к компоненту снова, Service Locator вернёт тот же экземпляр. |
||||
|
||||
|
||||
Что бы проверить, был ли идентификатор (ID) компонента уже зарегистрирован, можно использовать [[yii\di\ServiceLocator::has()]]. |
||||
Если вы вызовете [[yii\di\ServiceLocator::get()]] с недопустимым идентификатором (ID), тогда будет выброшено исключение. |
||||
|
||||
|
||||
|
||||
Поскольку Service Locator`ы зачастую создаются с [конфигурациями](concept-configurations.md), |
||||
записываемое свойство с именем [[yii\di\ServiceLocator::setComponents()|components]] предоставляется так, |
||||
что Вы можете его настроить и зарегистрировать несколько компонентов одновременно. |
||||
Следующий код демонстрирует конфигурационный массив, |
||||
который может использоваться для настройки приложения и регистрации компонентов "db", "cache" и "search" : |
||||
|
||||
```php |
||||
return [ |
||||
// ... |
||||
'components' => [ |
||||
'db' => [ |
||||
'class' => 'yii\db\Connection', |
||||
'dsn' => 'mysql:host=localhost;dbname=demo', |
||||
'username' => 'root', |
||||
'password' => '', |
||||
], |
||||
'cache' => 'yii\caching\ApcCache', |
||||
'search' => function () { |
||||
return new app\components\SolrService; |
||||
}, |
||||
], |
||||
]; |
||||
``` |
@ -0,0 +1,201 @@
|
||||
Виджеты |
||||
======= |
||||
|
||||
Виджеты представляют собой многоразовые строительные блоки, используемые в [представлениях](structure-views.md) |
||||
для создания сложных и настраиваемых элементов пользовательского интерфейса в рамках объектно-ориентированного |
||||
подхода. Например, виджет выбора даты (date picker) позволяет генерировать интерактивный интерфейс для выбора дат, |
||||
предоставляя пользователям приложения удобный способ для ввода данных такого типа. Все, что нужно для |
||||
подключения виджета - это добавить следующий код в представление: |
||||
|
||||
```php |
||||
<?php |
||||
use yii\bootstrap\DatePicker; |
||||
?> |
||||
<?= DatePicker::widget(['name' => 'date']) ?> |
||||
``` |
||||
|
||||
В комплект Yii входит большое количество виджетов, например: [[yii\widgets\ActiveForm|active form]], |
||||
[[yii\widgets\Menu|menu]], [виджеты jQuery UI](widget-jui.md), [виджеты Twitter Bootstrap](widget-bootstrap.md). |
||||
Далее будут представлены базовые сведения о виджетах. Для получения сведений относительно использования |
||||
конкретного виджета, следует обратиться к документации соответствующего класса. |
||||
|
||||
|
||||
## Использование Виджетов <a name="using-widgets"></a> |
||||
|
||||
Главным образом, виджеты применяют в [представлениях](structure-views.md). Для того, чтобы использовать виджет |
||||
в представлении, достаточно вызвать метод [[yii\base\Widget::widget()]]. Метод принимает массив [настроек](concept-configurations.md) |
||||
для инициализации виджета и возвращает результат его рендеринга. Например, следующий |
||||
код добавляет виджет для выбора даты, сконфигурированный для использования русского в качестве языка интерфейса |
||||
виджета и хранения вводимых данных в атрибуте `from_date` модели `$model`. |
||||
|
||||
```php |
||||
<?php |
||||
use yii\bootstrap\DatePicker; |
||||
?> |
||||
<?= DatePicker::widget([ |
||||
'model' => $model, |
||||
'attribute' => 'from_date', |
||||
'language' => 'ru', |
||||
'clientOptions' => [ |
||||
'dateFormat' => 'yy-mm-dd', |
||||
], |
||||
]) ?> |
||||
``` |
||||
|
||||
Некоторые виджеты могут иметь внутреннее содержимое, которое следует располагать между вызовами методов |
||||
[[yii\base\Widget::begin()]] и [[yii\base\Widget::end()]]. Например, для генерации формы входа, в следующем |
||||
фрагменте кода используется виджет [[yii\widgets\ActiveForm]]. Этот виджет сгенерирует открывающий и закрывающий |
||||
тэги `<form>` в местах вызова методов `begin()` и `end()` соответственно. При этом, содержимое, расположенное |
||||
между вызовами указанных методов будет выведено без каких-либо изменений. |
||||
|
||||
```php |
||||
<?php |
||||
use yii\widgets\ActiveForm; |
||||
use yii\helpers\Html; |
||||
?> |
||||
|
||||
<?php $form = ActiveForm::begin(['id' => 'login-form']); ?> |
||||
|
||||
<?= $form->field($model, 'username') ?> |
||||
|
||||
<?= $form->field($model, 'password')->passwordInput() ?> |
||||
|
||||
<div class="form-group"> |
||||
<?= Html::submitButton('Login') ?> |
||||
</div> |
||||
|
||||
<?php ActiveForm::end(); ?> |
||||
``` |
||||
|
||||
Обратите внимание на то, что в отличие от метода [[yii\base\Widget::widget()]], который возвращает результат |
||||
рендеринга, метод [[yii\base\Widget::begin()]] возвращает экземпляр виджета, который может быть |
||||
использован в дальнейшем для формирования его внутреннего содержимого. |
||||
|
||||
|
||||
## Создание Виджетов <a name="creating-widgets"></a> |
||||
|
||||
Для того, чтобы создать виджет, следует унаследовать класс [[yii\base\Widget]] и переопределить методы |
||||
[[yii\base\Widget::init()]] и/или [[yii\base\Widget::run()]]. Как правило, метод `init()` должен содержать |
||||
код, выполняющий нормализацию свойств виджета, а метод `run()` - код, возвращающий результат рендеринга виджета. |
||||
Результат рендеринга может быть выведен непосредственно с помощью конструкции "echo" или же возвращен |
||||
в строке методом `run()`. |
||||
|
||||
В следующем примере, виджет `HelloWidget` HTML-кодирует и отображает содержимое, присвоенное свойству `message`. |
||||
В случае, если указанное свойство не установлено, виджет, в качестве значения по умолчанию отобразит строку "Hello World". |
||||
|
||||
```php |
||||
namespace app\components; |
||||
|
||||
use yii\base\Widget; |
||||
use yii\helpers\Html; |
||||
|
||||
class HelloWidget extends Widget |
||||
{ |
||||
public $message; |
||||
|
||||
public function init() |
||||
{ |
||||
parent::init(); |
||||
if ($this->message === null) { |
||||
$this->message = 'Hello World'; |
||||
} |
||||
} |
||||
|
||||
public function run() |
||||
{ |
||||
return Html::encode($this->message); |
||||
} |
||||
} |
||||
``` |
||||
|
||||
Для того, что бы использовать этот виджет, достаточно добавить в представление следующий код: |
||||
|
||||
```php |
||||
<?php |
||||
use app\components\HelloWidget; |
||||
?> |
||||
<?= HelloWidget::widget(['message' => 'Good morning']) ?> |
||||
``` |
||||
|
||||
Ниже представлен вариант виджета `HelloWidget`, который принимает содержимое, обрамленное вызовами методов |
||||
`begin()` и `end()`, HTML-кодирует его и выводит. |
||||
|
||||
```php |
||||
namespace app\components; |
||||
|
||||
use yii\base\Widget; |
||||
use yii\helpers\Html; |
||||
|
||||
class HelloWidget extends Widget |
||||
{ |
||||
public function init() |
||||
{ |
||||
parent::init(); |
||||
ob_start(); |
||||
} |
||||
|
||||
public function run() |
||||
{ |
||||
$content = ob_get_clean(); |
||||
return Html::encode($content); |
||||
} |
||||
} |
||||
``` |
||||
|
||||
Как Вы можете видеть, в методе `init()` происходит включение буферизации вывода PHP таким образом, что весь вывод |
||||
между вызовами `init()` и `run()` может быть перехвачен, обработан и возвращен в `run()`. |
||||
|
||||
> Информация: При вызове метода [[yii\base\Widget::begin()]] будет создан новый экземпляр виджета, при этом |
||||
вызов метода `init()` произойдет сразу после выполнения остального кода в конструкторе виджета. |
||||
При вызове метода [[yii\base\Widget::end()]], будет вызван метод `run()`, а возвращенное им значение будет выведено |
||||
методом `end()`. |
||||
|
||||
Следующий фрагмент кода содержит пример использования модифицированного варианта `HelloWidget`: |
||||
|
||||
```php |
||||
<?php |
||||
use app\components\HelloWidget; |
||||
?> |
||||
<?php HelloWidget::begin(); ?> |
||||
|
||||
content that may contain <tag>'s |
||||
|
||||
<?php HelloWidget::end(); ?> |
||||
``` |
||||
|
||||
В некоторых случаях, виджету может потребоваться вывести крупный блок содержимого. И хотя это содержимое может |
||||
быть встроено непосредственно в метод `run()`, целесообразней поместить его в [представление](structure-views.md) |
||||
и вызвать метод [[yii\base\Widget::render()]] для его рендеринга. Например, |
||||
|
||||
```php |
||||
public function run() |
||||
{ |
||||
return $this->render('hello'); |
||||
} |
||||
``` |
||||
|
||||
По умолчанию, файлы представлений виджетов должны находиться в директории `WidgetPath/views`, где `WidgetPath` - |
||||
директория, содержащая файл класса виджета. Таким образом, в приведенном выше примере, для виджета будет |
||||
использован файл представления `@app/components/views/hello.php`, при этом файл с классом виджета расположен в |
||||
`@app/components`. Для того, что бы изменить директорию, в которой содержатся файлы-представления для виджета, |
||||
следует переопределить метод [[yii\base\Widget::getViewPath()]]. |
||||
|
||||
|
||||
## Лучшие Практики <a name="best-practices"></a> |
||||
|
||||
Виджеты представляют собой объектно-ориентированный подход к повторному использованию кода пользовательского |
||||
интерфейса. |
||||
|
||||
При создании виджетов, следует придерживаться основных принципов концепции MVC. В общем случае, основную логику |
||||
следует располагать в классе виджета, разделяя при этом код, отвечающий за разметку в [представления](structure-views.md). |
||||
|
||||
Разрабатываемые виджеты должны быть самодостаточными. Это означает, что для их использования должно быть |
||||
достаточно всего лишь добавить виджет в представление. Добиться этого бывает затруднительно в том случае, |
||||
когда для его функционирования требуются внешние ресурсы, такие как CSS, JavaScript, изображения и т.д. |
||||
К счастью, Yii предоставляет поддержку механизма для работы с ресурсами [asset bundles](structure-asset-bundles.md), |
||||
который может быть успешно использован для решения данной проблемы. |
||||
|
||||
В случае, когда виджет не содержит логики, а содержит только код, отвечающий за вывод разметки, он мало |
||||
отличается от [представления](structure-views.md). В действительности, единственное его отличие состоит в том, что |
||||
виджет представляет собой отдельный и удобный для распространения класс, в то время как представление - это |
||||
обычный PHP скрипт, подходящий для использования только лишь в конретном приложении. |
@ -0,0 +1,52 @@
|
||||
Що таке Yii? |
||||
============ |
||||
|
||||
Yii – це високопродуктивний компонентний PHP фреймворк, призначений для швидкої розробки сучасних веб додатків. |
||||
Слово Yii (вимовляється як `Йі` `[ji:]`) в китайській мові означає "простий та еволюційний". |
||||
Також Yii може розшифровуватись акронім **Yes It Is**! |
||||
|
||||
|
||||
Для яких завдань найбільше підходить Yii? |
||||
----------------------------------------- |
||||
|
||||
Yii – це універсальний фреймворк і може бути задіяний у всіх типах веб додатків. Завдяки його компонентній структурі |
||||
і відмінній підтримці кешування, фреймворк особливо підходить для розробки таких великих проектів як портали, |
||||
форуми, CMS, магазини або RESTful-додатки. |
||||
|
||||
|
||||
Порівняння Yii з іншими фреймворками |
||||
------------------------------------ |
||||
|
||||
- Як і багато інших PHP фреймворків, для організації коду Yii використовує модель MVC (Model-View-Controller). |
||||
- Yii дотримується філософії простого й елегантного коду, не намагаючись ускладнювати дизайн тільки заради слідування |
||||
будь-яким шаблонами проектування. |
||||
- Yii є full-stack фреймворком і включає в себе перевірені можливості, які добре себе зарекомендували, |
||||
такі як ActiveRecord для реляційних та NoSQL баз даних, підтримку REST API, багаторівневе кешування та інші. |
||||
- Yii відмінно розширюваний. Ви можете налаштувати або замінити практично будь-яку частину основного коду. |
||||
Використовуючи архітектуру розширень - легко ділитися кодом або використовувати код спільноти. |
||||
- Висока продуктивність завжди є головною ціллю Yii. |
||||
|
||||
Yii — не проект однієї людини. Він підтримується і розвивається [сильною командою][] і великою спільнотою розробників, |
||||
які їй допомагають. Розробники фреймворка стежать за тенденціями веб розробки і розвитком інших проектів. |
||||
Найбільш значимі можливості і кращі практики регулярно впроваджуються у фреймворк у вигляді простих і елегантних інтерфейсів. |
||||
|
||||
[сильна команда розробників]: http://www.yiiframework.com/about/ |
||||
|
||||
Версії Yii |
||||
---------- |
||||
|
||||
На даний момент існує дві основні гілки Yii: 1.1 та 2.0. Гілка 1.1 є попереднім поколінням і знаходиться у стані підтримки. |
||||
Версія 2.0 - це повністю переписаний Yii, що використовує останні технології і протоколи, такі як Composer, PSR, простори імен, |
||||
типажі (traits) і багато іншого. 2.0 - останнє покоління фреймворка. На цій версії будуть зосереджені основні зусилля |
||||
кілька наступних років. Даний посібник призначений в основному версії 2.0. |
||||
|
||||
|
||||
Вимоги до ПЗ і знань |
||||
-------------------- |
||||
|
||||
Yii 2.0 потребує PHP 5.4.0 та вище. Щоб дізнатися вимоги для окремих можливостей ви можете запустити скрипт перевірки вимог, |
||||
який поставляється із кожним релізом фреймворка. |
||||
|
||||
Для розробки на Yii буде потрібне загальне розуміння ООП, так як фреймворк повністю слідує цій парадигмі. |
||||
Також слід вивчити такі сучасні можливості PHP як [простори імен](http://www.php.net/manual/en/language.namespaces.php) |
||||
і [типажі](http://www.php.net/manual/en/language.oop5.traits.php). |
@ -1,39 +0,0 @@
|
||||
Helper Classes |
||||
============== |
||||
|
||||
> Note: This section is under development. |
||||
|
||||
Yii provides many classes that help simplify common coding tasks, such as string or array manipulations, |
||||
HTML code generation, and so forth. These helper classes are organized under the `yii\helpers` namespace and |
||||
are all static classes (meaning they contain only static properties and methods and should not be instantiated). |
||||
|
||||
|
||||
You use a helper class by directly calling one of its static methods: |
||||
|
||||
|
||||
``` |
||||
use yii\helpers\ArrayHelper; |
||||
|
||||
$c = ArrayHelper::merge($a, $b); |
||||
``` |
||||
|
||||
Extending Helper Classes |
||||
------------------------ |
||||
|
||||
To make helper classes easier to extend, Yii breaks each helper class into two classes: a base class (e.g. `BaseArrayHelper`) |
||||
and a concrete class (e.g. `ArrayHelper`). When you use a helper, you should only use the concrete version, never use the base class. |
||||
|
||||
If you want to customize a helper, perform the following steps (using `ArrayHelper` as an example): |
||||
|
||||
1. Name your class the same as the concrete class provided by Yii, including the namespace: `yii\helpers\ArrayHelper` |
||||
2. Extend your class from the base class: `class ArrayHelper extends \yii\helpers\BaseArrayHelper`. |
||||
3. In your class, override any method or property as needed, or add new methods or properties. |
||||
4. Tell your application to use your version of the helper class by including the following line of code in the bootstrap script: |
||||
|
||||
```php |
||||
Yii::$classMap['yii\helpers\ArrayHelper'] = 'path/to/ArrayHelper.php'; |
||||
``` |
||||
|
||||
Step 4 above will instruct the Yii class autoloader to load your version of the helper class instead of the one included in the Yii distribution. |
||||
|
||||
> Tip: You can use `Yii::$classMap` to replace ANY core Yii class with your own customized version, not just helper classes. |
@ -0,0 +1,37 @@
|
||||
<?php |
||||
namespace yiiunit\framework\rbac; |
||||
|
||||
use yii\rbac\PhpManager; |
||||
|
||||
/** |
||||
* Exposes protected properties and methods to inspect from outside |
||||
*/ |
||||
class ExposedPhpManager extends PhpManager |
||||
{ |
||||
/** |
||||
* @var \yii\rbac\Item[] |
||||
*/ |
||||
public $items = []; // itemName => item |
||||
/** |
||||
* @var array |
||||
*/ |
||||
public $children = []; // itemName, childName => child |
||||
/** |
||||
* @var \yii\rbac\Assignment[] |
||||
*/ |
||||
public $assignments = []; // userId, itemName => assignment |
||||
/** |
||||
* @var \yii\rbac\Rule[] |
||||
*/ |
||||
public $rules = []; // ruleName => rule |
||||
|
||||
public function load() |
||||
{ |
||||
parent::load(); |
||||
} |
||||
|
||||
public function save() |
||||
{ |
||||
parent::save(); |
||||
} |
||||
} |
Loading…
Reference in new issue