Translate guide of service locator and start to translate properties section [skip ci]

parent cb5d6f79
属性(Property)
==========
In PHP, class member variables are also called *properties*. These variables are part of the class definition, and are used
to represent the state of a class instance (i.e., to differentiate one instance of the class from another). In practice, you may often want to handle the reading or writing of properties in special ways. For example, you may want to trim a string when it is being assigned
to a `label` property. You could use the following code to achieve this task:
```php
$object->label = trim($label);
```
The drawback of the above code is that you have to call `trim()` everywhere in your code where you met 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.
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 such support, it should extend from
[[yii\base\Object]] or a child class.
> Info: Nearly every core class in the Yii framework extends from [[yii\base\Object]] or a child class.
This means that whenever you see a getter or setter in a core class, you can use it like a property.
A getter method is a method whose name starts with the word `get`; a setter method starts with `set`.
The name after the `get` or `set` prefix defines the name of a property. For example, a getter `getLabel()` and/or
a setter `setLabel()` defines a property named `label`, as shown in the following code:
```php
namespace app\components;
use yii\base\Object;
class Foo extend Object
{
private $_label;
public function getLabel()
{
return $this->_label;
}
public function setLabel($value)
{
$this->_label = trim($value);
}
}
```
(To be clear, the getter and setter methods create the property `label`, which in this case internally refer to a private attributed named `_label`.)
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
being assigned a value, the corresponding setter method will be called. For example:
```php
// equivalent to $label = $object->getLabel();
$label = $object->label;
// equivalent to $object->setLabel('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
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
properties.
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.
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.
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.
* 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.
* The properties can only be defined by *non-static* getters and/or setters. Static methods will not be treated in this 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()` 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`.
服务定位器(Service Locator)
===============
服务定位器是一个了解如何提供各种应用所需的服务(或组件)的对象。在一个服务定位器中,每一个组件都只有一个单独的实例,并通过
ID 唯一地标识。用这个 ID 就能从服务定位器中得到这个组件。
在 Yii 中,服务定位器只是 [[yii\di\ServiceLocator]] 或其子类的一个实例。
最最常用的服务定位器一般是 *application(应用)* 对象,可以通过 `\Yii::$app` 访问。它所提供的服务被称为
*application components(应用组件)*,比如:`request``response``urlManager`(分别是请求、响应、Url 管理器)组件。你可以通过服务定位器所提供的功能,非常容易地配置这些组件,或甚至是用你自己的实现替换掉他们。
除了 Application 对象,每一个模块对象本身也是一个服务定位器。
要使用一个服务定位器,第一步是要注册相关组件。组件可以通过 [[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]] 会通过该组件的注册信息创建一个该组件的实例,并返回它。之后,如果再次访问,则服务定位器会返回同一个实例。
你可以通过 [[yii\di\ServiceLocator::has()]] 检查某组件 ID 是否被注册。
若你用一个无效的 ID 调用 [[yii\di\ServiceLocator::get()]],则会抛出一个异常。
因为服务定位器,经常会在创建时附带[配置信息](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;
},
],
];
```
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