Commit 44d2d7a4 by Nobuo Kihara

Merge branch 'master' into ja-2014-10-15

parents 6f1efd18 187aed7d
...@@ -83,7 +83,7 @@ if ($this->beginCache($id, ['variations' => [Yii::$app->language]])) { ...@@ -83,7 +83,7 @@ if ($this->beginCache($id, ['variations' => [Yii::$app->language]])) {
### Переключение кэширования <a name="toggling-caching"></a> ### Переключение кэширования <a name="toggling-caching"></a>
Иногда может потребоваться включать кширование фрагментов только для определённых условий. Например, страницу с формой мы хотим кэшировать только тогда, когда обращение к ней произошло впервые (посредством GET запроса). Любое последующее отображение формы (посредством POST запроса) не должно быть кэшировано, потому что может содержать данные, введённые пользователем. Для этого мы задаём параметр [[yii\widgets\FragmentCache::enabled|enabled]]: Иногда может потребоваться включать кеширование фрагментов только для определённых условий. Например, страницу с формой мы хотим кэшировать только тогда, когда обращение к ней произошло впервые (посредством GET запроса). Любое последующее отображение формы (посредством POST запроса) не должно быть кэшировано, потому что может содержать данные, введённые пользователем. Для этого мы задаём параметр [[yii\widgets\FragmentCache::enabled|enabled]]:
```php ```php
if ($this->beginCache($id, ['enabled' => Yii::$app->request->isGet])) { if ($this->beginCache($id, ['enabled' => Yii::$app->request->isGet])) {
......
...@@ -24,8 +24,7 @@ Yii – это универсальный фреймворк и может бы ...@@ -24,8 +24,7 @@ Yii – это универсальный фреймворк и может бы
шаблонам проектирования. шаблонам проектирования.
- Yii является full-stack фреймворком и включает в себя проверенные и хорошо зарекомендовавшие себя возможности, такие как - Yii является full-stack фреймворком и включает в себя проверенные и хорошо зарекомендовавшие себя возможности, такие как
ActiveRecord для реляционных и NoSQL баз данных, поддержку REST API, многоуровневое кеширование и другие. ActiveRecord для реляционных и NoSQL баз данных, поддержку REST API, многоуровневое кеширование и другие.
- Yii отлично расширяем. Вы можете настроить или заменить практически любую часть основного кода. Используя архитектуру - Yii отлично расширяем. Вы можете настроить или заменить практически любую часть основного кода. Используя архитектуру расширений легко делиться кодом или использовать код сообщества.
расшрений легко делиться кодом или использовать код сообщества.
- Одна из главных целей Yii – производительность. - Одна из главных целей Yii – производительность.
Yii — не проект одного человека. Он поддерживается и развивается [сильной командой][] и большим сообществом разработчиков, Yii — не проект одного человека. Он поддерживается и развивается [сильной командой][] и большим сообществом разработчиков,
......
...@@ -562,7 +562,7 @@ $this->registerLinkTag([ ...@@ -562,7 +562,7 @@ $this->registerLinkTag([
- [[yii\base\View::EVENT_BEFORE_RENDER|EVENT_BEFORE_RENDER]]: вызывается в начале рендеринга файла в контроллере. - [[yii\base\View::EVENT_BEFORE_RENDER|EVENT_BEFORE_RENDER]]: вызывается в начале рендеринга файла в контроллере.
Обработчики этого события могут придать атрибуту [[yii\base\ViewEvent::isValid]] значение `false`, чтобы отменить процесс рендеринга. Обработчики этого события могут придать атрибуту [[yii\base\ViewEvent::isValid]] значение `false`, чтобы отменить процесс рендеринга.
- [[yii\base\View::EVENT_AFTER_RENDER|EVENT_AFTER_RENDER]]: событие инициируется вызовом [[yii\base\View::beginPage()]] в шаблонах. - [[yii\base\View::EVENT_AFTER_RENDER|EVENT_AFTER_RENDER]]: событие инициируется после рендеринга файла вызовом [[yii\base\View::afterRender()]].
Обработчики события могут получать результат рендеринга через [[yii\base\ViewEvent::output]] и могут изменять это свойство для изменения Обработчики события могут получать результат рендеринга через [[yii\base\ViewEvent::output]] и могут изменять это свойство для изменения
результата рендеринга. результата рендеринга.
- [[yii\base\View::EVENT_BEGIN_PAGE|EVENT_BEGIN_PAGE]]: инициируется вызовом [[yii\base\View::beginPage()]] в шаблонах. - [[yii\base\View::EVENT_BEGIN_PAGE|EVENT_BEGIN_PAGE]]: инициируется вызовом [[yii\base\View::beginPage()]] в шаблонах.
......
...@@ -130,7 +130,7 @@ an [entry script](structure-entry-scripts.md), where the class name is already g ...@@ -130,7 +130,7 @@ an [entry script](structure-entry-scripts.md), where the class name is already g
(new yii\web\Application($config))->run(); (new yii\web\Application($config))->run();
``` ```
For more details about configuring the `components` property of an application can be found More details about configuring the `components` property of an application can be found
in the [Applications](structure-applications.md) section and the [Service Locator](concept-service-locator.md) section. in the [Applications](structure-applications.md) section and the [Service Locator](concept-service-locator.md) section.
...@@ -153,7 +153,7 @@ echo Menu::widget([ ...@@ -153,7 +153,7 @@ echo Menu::widget([
]); ]);
``` ```
The above code creates a `Menu` widget and initializes its `activeItems` property to be false. The above code creates a `Menu` widget and initializes its `activateItems` property to be false.
The `items` property is also configured with menu items to be displayed. The `items` property is also configured with menu items to be displayed.
Note that because the class name is already given, the configuration array should NOT have the `class` key. Note that because the class name is already given, the configuration array should NOT have the `class` key.
...@@ -215,7 +215,7 @@ $config = require('path/to/web.php'); ...@@ -215,7 +215,7 @@ $config = require('path/to/web.php');
## Default Configurations <a name="default-configurations"></a> ## Default Configurations <a name="default-configurations"></a>
The [[Yii::createObject()]] method is implemented based on a [dependency injection container](concept-di-container.md). The [[Yii::createObject()]] method is implemented based on a [dependency injection container](concept-di-container.md).
It allows you to specify a set of the so-called *default configurations* which will be applied to ANY instances of It allows you to specify a set of the so-called *default configurations* which will be applied to ALL instances of
the specified classes when they are being created using [[Yii::createObject()]]. The default configurations the specified classes when they are being created using [[Yii::createObject()]]. The default configurations
can be specified by calling `Yii::$container->set()` in the [bootstrapping](runtime-bootstrapping.md) code. can be specified by calling `Yii::$container->set()` in the [bootstrapping](runtime-bootstrapping.md) code.
......
...@@ -202,7 +202,7 @@ Sometimes, you may want to respond to an event triggered by *every* instance of ...@@ -202,7 +202,7 @@ Sometimes, you may want to respond to an event triggered by *every* instance of
a specific instance. Instead of attaching an event handler to every instance, you may attach the handler a specific instance. Instead of attaching an event handler to every instance, you may attach the handler
on the *class level* by calling the static method [[yii\base\Event::on()]]. on the *class level* by calling the static method [[yii\base\Event::on()]].
For example, an [Active Record](db-active-record.md) object will trigger an [[yii\base\ActiveRecord::EVENT_AFTER_INSERT]] For example, an [Active Record](db-active-record.md) object will trigger an [[yii\db\BaseActiveRecord::EVENT_AFTER_INSERT|EVENT_AFTER_INSERT]]
event whenever it inserts a new record into the database. In order to track insertions done by *every* event whenever it inserts a new record into the database. In order to track insertions done by *every*
[Active Record](db-active-record.md) object, you may use the following code: [Active Record](db-active-record.md) object, you may use the following code:
...@@ -216,8 +216,8 @@ Event::on(ActiveRecord::className(), ActiveRecord::EVENT_AFTER_INSERT, function ...@@ -216,8 +216,8 @@ Event::on(ActiveRecord::className(), ActiveRecord::EVENT_AFTER_INSERT, function
}); });
``` ```
The event handler will be invoked whenever an instance of [[yii\base\ActiveRecord|ActiveRecord]], or one of its child classes, triggers The event handler will be invoked whenever an instance of [[yii\db\ActiveRecord|ActiveRecord]], or one of its child classes, triggers
the [[yii\base\ActiveRecord::EVENT_AFTER_INSERT|EVENT_AFTER_INSERT]] event. In the handler, you can get the object the [[yii\db\BaseActiveRecord::EVENT_AFTER_INSERT|EVENT_AFTER_INSERT]] event. In the handler, you can get the object
that triggered the event through `$event->sender`. that triggered the event through `$event->sender`.
When an object triggers an event, it will first call instance-level handlers, followed by the class-level handlers. When an object triggers an event, it will first call instance-level handlers, followed by the class-level handlers.
......
...@@ -10,7 +10,7 @@ $object->label = trim($label); ...@@ -10,7 +10,7 @@ $object->label = trim($label);
``` ```
The drawback of the above code is that you would have to call `trim()` everywhere in your code where you might set the `label` The drawback of the above code is that you would have to call `trim()` everywhere in your code where you might set the `label`
property. If, in the future, the `label` property gets a new requirement, such as the first letter must be captialized, you would again have to modify every bit of code that assigns a value to `label`. The repetition of code leads to bugs, and is a practice you want to avoid as much as possible. property. If, in the future, the `label` property gets a new requirement, such as the first letter must be capitalized, you would again have to modify every bit of code that assigns a value to `label`. The repetition of code leads to bugs, and is a practice you want to avoid as much as possible.
To solve this problem, Yii introduces a base class called [[yii\base\Object]] that supports defining properties To solve this problem, Yii introduces a base class called [[yii\base\Object]] that supports defining properties
based on *getter* and *setter* class methods. If a class needs that functionality, it should extend from based on *getter* and *setter* class methods. If a class needs that functionality, it should extend from
...@@ -28,7 +28,7 @@ namespace app\components; ...@@ -28,7 +28,7 @@ namespace app\components;
use yii\base\Object; use yii\base\Object;
class Foo extend Object class Foo extends Object
{ {
private $_label; private $_label;
...@@ -44,10 +44,10 @@ class Foo extend Object ...@@ -44,10 +44,10 @@ class Foo extend Object
} }
``` ```
(To be clear, the getter and setter methods create the property `label`, which in this case internally refer to a private attributed named `_label`.) (To be clear, the getter and setter methods create the property `label`, which in this case internally refers to a private attribute named `_label`.)
Properties defined by getters and setters can be used like class member variables. The main difference is that Properties defined by getters and setters can be used like class member variables. The main difference is that
when such a property is being read, the corresponding getter method will be called; when the property is when such property is being read, the corresponding getter method will be called; when the property is
being assigned a value, the corresponding setter method will be called. For example: being assigned a value, the corresponding setter method will be called. For example:
```php ```php
...@@ -58,20 +58,20 @@ $label = $object->label; ...@@ -58,20 +58,20 @@ $label = $object->label;
$object->label = 'abc'; $object->label = 'abc';
``` ```
A property defined by a getter without a setter is *read only*. Trying to assign a value to such a property will cause A property defined by a getter without a setter is *read only*. Trying to assign a value to such property will cause
an [[yii\base\InvalidCallException|InvalidCallException]]. Similarly, a property defined by a setter without a getter an [[yii\base\InvalidCallException|InvalidCallException]]. Similarly, a property defined by a setter without a getter
is *write only*, and trying to read such a property will also cause an exception. It is not common to have write-only is *write only*, and trying to read such property will also cause an exception. It is not common to have write-only
properties. properties.
There are several special rules for, and limitations on, the properties defined via getters and setters: There are several special rules for, and limitations on, the properties defined via getters and setters:
* The names of such properties are *case-insensitive*. For example, `$object->label` and `$object->Label` are the same. * The names of such properties are *case-insensitive*. For example, `$object->label` and `$object->Label` are the same.
This is because method names in PHP are case-insensitive. This is because method names in PHP are case-insensitive.
* If the name of such a property is the same as a class member variable, the latter will take precedence. * If the name of such property is the same as a class member variable, the latter will take precedence.
For example, if the above `Foo` class has a member variable `label`, then the assignment `$object->label = 'abc'` For example, if the above `Foo` class has a member variable `label`, then the assignment `$object->label = 'abc'`
will affect the *member variable* 'label'; that line would not call the `setLabel()` setter method. will affect the *member variable* 'label'; that line would not call the `setLabel()` setter method.
* These properties do not support visibility. It makes no difference for the visibility of a property * These properties do not support visibility. It makes no difference for the visibility of a property
if the defining getter or setter method is public, protected or private. if the defining getter or setter method is public, protected or private.
* The properties can only be defined by *non-static* getters and/or setters. Static methods will not be treated in this same manner. * The properties can only be defined by *non-static* getters and/or setters. Static methods will not be treated in the same manner.
Returning back to the problem described at the beginning of this guide, instead of calling `trim()` everywhere a `label` value is assigned, `trim()` now only needs to be invoked within the setter `setLabel()`. And if a new requirement comes that requires the label be initially capitalized, the `setLabel()` method can quickly be modified without touching any other code. The one change will universally affect every assignment to `label`. Returning back to the problem described at the beginning of this guide, instead of calling `trim()` everywhere a `label` value is assigned, `trim()` now only needs to be invoked within the setter `setLabel()`. And if a new requirement comes that requires the label to be initially capitalized, the `setLabel()` method can quickly be modified without touching any other code. The one change will universally affect every assignment to `label`.
...@@ -3,13 +3,15 @@ Creating your own Application structure ...@@ -3,13 +3,15 @@ Creating your own Application structure
> Note: This section is under development. > Note: This section is under development.
While the [basic](apps-basic.md) and [advanced](apps-advanced.md) application templates are great for most of your needs, While the [basic](https://github.com/yiisoft/yii2/tree/master/apps/basic) and [advanced](https://github.com/yiisoft/yii2/tree/master/apps/advanced)
you may want to create your own application template with which to start your projects. application templates are great for most of your needs, you may want to create your own application template with which
to start your projects.
Application templates in Yii are simply repositories containing a `composer.json` file, and registered as a Composer package. Any repository can be identified as a Composer package, making it installable via `create-project` Composer command. Application templates in Yii are simply repositories containing a `composer.json` file, and registered as a Composer package.
Any repository can be identified as a Composer package, making it installable via `create-project` Composer command.
Since it's a bit too much to start building your entire template from scratch, it is better to use one of the built-in templates Since it's a bit too much to start building your entire template from scratch, it is better to use one of the built-in
as a base. Let's use the basic template here. templates as a base. Let's use the basic template here.
Clone the Basic Template Clone the Basic Template
---------------------------------------- ----------------------------------------
...@@ -37,10 +39,10 @@ Next, actually modify the structure and contents of the application as you would ...@@ -37,10 +39,10 @@ Next, actually modify the structure and contents of the application as you would
Make a Package 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://githumb.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/). 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 packge. For instructions, see the [Composer documentation](https://getcomposer.org/doc/05-repositories.md#hosting-your-own). 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 Use the Template
------ ------
......
...@@ -21,8 +21,11 @@ component's behavior: ...@@ -21,8 +21,11 @@ component's behavior:
], ],
'twig' => [ 'twig' => [
'class' => 'yii\twig\ViewRenderer', 'class' => 'yii\twig\ViewRenderer',
//'cachePath' => '@runtime/Twig/cache', 'cachePath' => '@runtime/Twig/cache',
//'options' => [], /* Array of twig options */ // Array of twig options:
'options' => [
'auto_reload' => true,
],
'globals' => ['html' => '\yii\helpers\Html'], 'globals' => ['html' => '\yii\helpers\Html'],
'uses' => ['yii\bootstrap'], 'uses' => ['yii\bootstrap'],
], ],
......
...@@ -14,8 +14,11 @@ return [ ...@@ -14,8 +14,11 @@ return [
'twig' => [ 'twig' => [
'class' => 'yii\twig\ViewRenderer', 'class' => 'yii\twig\ViewRenderer',
// set cachePath to false in order to disable template caching // set cachePath to false in order to disable template caching
//'cachePath' => '@runtime/Twig/cache', 'cachePath' => '@runtime/Twig/cache',
//'options' => [], /* Array of twig options */ // Array of twig options:
'options' => [
'auto_reload' => true,
],
// ... see ViewRenderer for more options // ... see ViewRenderer for more options
], ],
], ],
......
...@@ -100,7 +100,7 @@ class FixtureController extends Controller ...@@ -100,7 +100,7 @@ class FixtureController extends Controller
* *
* @throws Exception if the specified fixture does not exist. * @throws Exception if the specified fixture does not exist.
*/ */
public function actionLoad() public function actionLoad($fixturesInput)
{ {
$fixturesInput = func_get_args(); $fixturesInput = func_get_args();
$filtered = $this->filterFixtures($fixturesInput); $filtered = $this->filterFixtures($fixturesInput);
......
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