類別 yii\di\ServiceLocator
ServiceLocator 實作了 服務定位器。
若要使用 ServiceLocator,您首先需要透過呼叫 set() 或 setComponents(),向定位器註冊組件 ID 及其對應的組件定義。然後您可以呼叫 get() 來檢索具有指定 ID 的組件。定位器將根據定義自動實例化和配置組件。
例如:
$locator = new \yii\di\ServiceLocator;
$locator->setComponents([
'db' => [
'class' => 'yii\db\Connection',
'dsn' => 'sqlite:path/to/file.db',
],
'cache' => [
'class' => 'yii\caching\DbCache',
'db' => 'db',
],
]);
$db = $locator->get('db'); // or $locator->db
$cache = $locator->get('cache'); // or $locator->cache
由於 yii\base\Module 繼承自 ServiceLocator,模組和應用程式都是服務定位器。模組為服務解析增加了樹狀遍歷。
有關 ServiceLocator 的更多詳細資訊和使用方法,請參閱關於服務定位器的指南文章。
公共屬性
屬性 | 類型 | 描述 | 定義於 |
---|---|---|---|
$behaviors | yii\base\Behavior[] | 附加到此組件的行為列表。 | yii\base\Component |
$components | array | 組件定義列表或已載入的組件實例 (ID => 定義或實例)。 | yii\di\ServiceLocator |
公共方法
屬性詳情
方法詳情
Defined in: yii\base\Component::__call()
呼叫非類別方法的具名方法。
此方法將檢查是否有任何附加的行為具有具名方法,並在可用的情況下執行它。
請勿直接呼叫此方法,因為它是 PHP 魔術方法,當調用未知方法時,將會隱含地呼叫它。
public mixed __call ( $name, $params ) | ||
$name | string |
方法名稱 |
$params | array |
方法參數 |
return | mixed |
方法傳回值 |
---|---|---|
throws | yii\base\UnknownMethodException |
當呼叫未知方法時 |
public function __call($name, $params)
{
$this->ensureBehaviors();
foreach ($this->_behaviors as $object) {
if ($object->hasMethod($name)) {
return call_user_func_array([$object, $name], $params);
}
}
throw new UnknownMethodException('Calling unknown method: ' . get_class($this) . "::$name()");
}
public void __clone ( ) |
public function __clone()
{
$this->_events = [];
$this->_eventWildcards = [];
$this->_behaviors = null;
}
Defined in: yii\base\BaseObject::__construct()
建構子。
預設實作會執行兩件事
- 使用給定的組態
$config
初始化物件。 - 呼叫 init()。
如果在子類別中覆寫此方法,建議
- 建構子的最後一個參數是組態陣列,例如此處的
$config
。 - 在建構子的結尾呼叫父類別實作。
public void __construct ( $config = [] ) | ||
$config | array |
將用於初始化物件屬性的名稱-值配對 |
public function __construct($config = [])
{
if (!empty($config)) {
Yii::configure($this, $config);
}
$this->init();
}
Getter 魔術方法。
覆寫此方法以支援像讀取屬性一樣存取元件。
public mixed __get ( $name ) | ||
$name | string |
元件或屬性名稱 |
return | mixed |
具名屬性值 |
---|
public function __get($name)
{
if ($this->has($name)) {
return $this->get($name);
}
return parent::__get($name);
}
檢查屬性值是否為 null。
此方法覆寫父類別實作,方法是檢查具名元件是否已載入。
public boolean __isset ( $name ) | ||
$name | string |
屬性名稱或事件名稱 |
return | boolean |
屬性值是否為 null |
---|
public function __isset($name)
{
if ($this->has($name)) {
return true;
}
return parent::__isset($name);
}
Defined in: yii\base\Component::__set()
設定組件屬性的值。
此方法將依以下順序檢查並採取相應動作
- setter 定義的屬性:設定屬性值
- 格式為 "on xyz" 的事件:將處理常式附加到事件 "xyz"
- 格式為 "as xyz" 的行為:附加名為 "xyz" 的行為
- 行為的屬性:設定行為屬性值
請勿直接呼叫此方法,因為它是 PHP 魔術方法,當執行 $component->property = $value;
時,將會隱含地呼叫它。
另請參閱 __get()。
public void __set ( $name, $value ) | ||
$name | string |
屬性名稱或事件名稱 |
$value | mixed |
屬性值 |
throws | yii\base\UnknownPropertyException |
如果未定義屬性 |
---|---|---|
throws | yii\base\InvalidCallException |
如果屬性為唯讀。 |
public function __set($name, $value)
{
$setter = 'set' . $name;
if (method_exists($this, $setter)) {
// set property
$this->$setter($value);
return;
} elseif (strncmp($name, 'on ', 3) === 0) {
// on event: attach event handler
$this->on(trim(substr($name, 3)), $value);
return;
} elseif (strncmp($name, 'as ', 3) === 0) {
// as behavior: attach behavior
$name = trim(substr($name, 3));
$this->attachBehavior($name, $value instanceof Behavior ? $value : Yii::createObject($value));
return;
}
// behavior property
$this->ensureBehaviors();
foreach ($this->_behaviors as $behavior) {
if ($behavior->canSetProperty($name)) {
$behavior->$name = $value;
return;
}
}
if (method_exists($this, 'get' . $name)) {
throw new InvalidCallException('Setting read-only property: ' . get_class($this) . '::' . $name);
}
throw new UnknownPropertyException('Setting unknown property: ' . get_class($this) . '::' . $name);
}
Defined in: yii\base\Component::__unset()
將組件屬性設定為 null。
此方法將依以下順序檢查並採取相應動作
- setter 定義的屬性:將屬性值設定為 null
- 行為的屬性:將屬性值設定為 null
請勿直接呼叫此方法,因為它是 PHP 魔術方法,當執行 unset($component->property)
時,將會隱含地呼叫它。
public void __unset ( $name ) | ||
$name | string |
屬性名稱 |
throws | yii\base\InvalidCallException |
如果屬性為唯讀。 |
---|
public function __unset($name)
{
$setter = 'set' . $name;
if (method_exists($this, $setter)) {
$this->$setter(null);
return;
}
// behavior property
$this->ensureBehaviors();
foreach ($this->_behaviors as $behavior) {
if ($behavior->canSetProperty($name)) {
$behavior->$name = null;
return;
}
}
throw new InvalidCallException('Unsetting an unknown or read-only property: ' . get_class($this) . '::' . $name);
}
Defined in: yii\base\Component::attachBehavior()
將行為附加到此組件。
此方法將根據給定的組態建立行為物件。之後,將透過呼叫 yii\base\Behavior::attach() 方法,將行為物件附加到此元件。
另請參閱 detachBehavior()。
public yii\base\Behavior attachBehavior ( $name, $behavior ) | ||
$name | string |
行為的名稱。 |
$behavior | string|array|yii\base\Behavior |
行為組態。可以是以下其中一項
|
return | yii\base\Behavior |
行為物件 |
---|
public function attachBehavior($name, $behavior)
{
$this->ensureBehaviors();
return $this->attachBehaviorInternal($name, $behavior);
}
Defined in: yii\base\Component::attachBehaviors()
將行為列表附加到組件。
每個行為都以其名稱索引,並且應該是 yii\base\Behavior 物件、指定行為類別的字串,或是用於建立行為的組態陣列。
另請參閱 attachBehavior()。
public void attachBehaviors ( $behaviors ) | ||
$behaviors | array |
要附加到元件的行為清單 |
public function attachBehaviors($behaviors)
{
$this->ensureBehaviors();
foreach ($behaviors as $name => $behavior) {
$this->attachBehaviorInternal($name, $behavior);
}
}
Defined in: yii\base\Component::behaviors()
傳回此組件應表現為的行為列表。
子類別可以覆寫此方法,以指定它們想要表現為的行為。
此方法的傳回值應為行為物件或組態的陣列,並以行為名稱索引。行為組態可以是指定行為類別的字串,或是以下結構的陣列
'behaviorName' => [
'class' => 'BehaviorClass',
'property1' => 'value1',
'property2' => 'value2',
]
請注意,行為類別必須從 yii\base\Behavior 擴充。行為可以使用名稱或匿名方式附加。當使用名稱作為陣列索引鍵時,可以使用此名稱,稍後使用 getBehavior() 擷取行為,或使用 detachBehavior() 卸離行為。匿名行為無法擷取或卸離。
在此方法中宣告的行為將會自動 (依需求) 附加到元件。
public array behaviors ( ) | ||
return | array |
行為組態。 |
---|
public function behaviors()
{
return [];
}
Defined in: yii\base\Component::canGetProperty()
傳回一個值,指示是否可以讀取屬性。
如果符合以下條件,則可以讀取屬性
- 類別具有與指定名稱相關聯的 getter 方法 (在此情況下,屬性名稱不區分大小寫);
- 類別具有具有指定名稱的成員變數 (當
$checkVars
為 true 時); - 附加的行為具有給定名稱的可讀屬性 (當
$checkBehaviors
為 true 時)。
另請參閱 canSetProperty()。
public boolean canGetProperty ( $name, $checkVars = true, $checkBehaviors = true ) | ||
$name | string |
屬性名稱 |
$checkVars | boolean |
是否將成員變數視為屬性 |
$checkBehaviors | boolean |
是否將行為的屬性視為此元件的屬性 |
return | boolean |
是否可以讀取屬性 |
---|
public function canGetProperty($name, $checkVars = true, $checkBehaviors = true)
{
if (method_exists($this, 'get' . $name) || $checkVars && property_exists($this, $name)) {
return true;
} elseif ($checkBehaviors) {
$this->ensureBehaviors();
foreach ($this->_behaviors as $behavior) {
if ($behavior->canGetProperty($name, $checkVars)) {
return true;
}
}
}
return false;
}
Defined in: yii\base\Component::canSetProperty()
傳回一個值,指示是否可以設定屬性。
如果符合以下條件,則可以寫入屬性
- 類別具有與指定名稱相關聯的 setter 方法 (在此情況下,屬性名稱不區分大小寫);
- 類別具有具有指定名稱的成員變數 (當
$checkVars
為 true 時); - 附加的行為具有給定名稱的可寫屬性 (當
$checkBehaviors
為 true 時)。
另請參閱 canGetProperty()。
public boolean canSetProperty ( $name, $checkVars = true, $checkBehaviors = true ) | ||
$name | string |
屬性名稱 |
$checkVars | boolean |
是否將成員變數視為屬性 |
$checkBehaviors | boolean |
是否將行為的屬性視為此元件的屬性 |
return | boolean |
是否可以寫入屬性 |
---|
public function canSetProperty($name, $checkVars = true, $checkBehaviors = true)
{
if (method_exists($this, 'set' . $name) || $checkVars && property_exists($this, $name)) {
return true;
} elseif ($checkBehaviors) {
$this->ensureBehaviors();
foreach ($this->_behaviors as $behavior) {
if ($behavior->canSetProperty($name, $checkVars)) {
return true;
}
}
}
return false;
}
::class
。
Defined in: yii\base\BaseObject::className()
傳回此類別的完整限定名稱。
public static string className ( ) | ||
return | string |
此類別的完整限定名稱。 |
---|
public static function className()
{
return get_called_class();
}
從定位器中移除組件。
public void clear ( $id ) | ||
$id | string |
元件 ID |
public function clear($id)
{
unset($this->_definitions[$id], $this->_components[$id]);
}
public yii\base\Behavior|null detachBehavior ( $name ) | ||
$name | string |
行為的名稱。 |
return | yii\base\Behavior|null |
卸離的行為。如果行為不存在,則為 Null。 |
---|
public function detachBehavior($name)
{
$this->ensureBehaviors();
if (isset($this->_behaviors[$name])) {
$behavior = $this->_behaviors[$name];
unset($this->_behaviors[$name]);
$behavior->detach();
return $behavior;
}
return null;
}
Defined in: yii\base\Component::detachBehaviors()
從組件分離所有行為。
public void detachBehaviors ( ) |
public function detachBehaviors()
{
$this->ensureBehaviors();
foreach ($this->_behaviors as $name => $behavior) {
$this->detachBehavior($name);
}
}
Defined in: yii\base\Component::ensureBehaviors()
確保在 behaviors() 中宣告的行為已附加到此組件。
public void ensureBehaviors ( ) |
public function ensureBehaviors()
{
if ($this->_behaviors === null) {
$this->_behaviors = [];
foreach ($this->behaviors() as $name => $behavior) {
$this->attachBehaviorInternal($name, $behavior);
}
}
}
public object|null get ( $id, $throwException = true ) | ||
$id | string |
元件 ID (例如 |
$throwException | boolean |
如果 |
return | object|null |
指定 ID 的元件。如果 |
---|---|---|
throws | yii\base\InvalidConfigException |
如果 |
public function get($id, $throwException = true)
{
if (isset($this->_components[$id])) {
return $this->_components[$id];
}
if (isset($this->_definitions[$id])) {
$definition = $this->_definitions[$id];
if (is_object($definition) && !$definition instanceof Closure) {
return $this->_components[$id] = $definition;
}
return $this->_components[$id] = Yii::createObject($definition);
} elseif ($throwException) {
throw new InvalidConfigException("Unknown component ID: $id");
}
return null;
}
Defined in: yii\base\Component::getBehavior()
傳回具名的行為物件。
public yii\base\Behavior|null getBehavior ( $name ) | ||
$name | string |
行為名稱 |
return | yii\base\Behavior|null |
行為物件,如果行為不存在,則為 null |
---|
public function getBehavior($name)
{
$this->ensureBehaviors();
return isset($this->_behaviors[$name]) ? $this->_behaviors[$name] : null;
}
Defined in: yii\base\Component::getBehaviors()
傳回附加到此組件的所有行為。
public yii\base\Behavior[] getBehaviors ( ) | ||
return | yii\base\Behavior[] |
附加到此元件的行為清單 |
---|
public function getBehaviors()
{
$this->ensureBehaviors();
return $this->_behaviors;
}
傳回組件定義列表或已載入的組件實例。
public array getComponents ( $returnDefinitions = true ) | ||
$returnDefinitions | boolean |
是否傳回元件定義,而不是已載入的元件實例。 |
return | array |
組件定義列表或已載入的組件實例 (ID => 定義或實例)。 |
---|
public function getComponents($returnDefinitions = true)
{
return $returnDefinitions ? $this->_definitions : $this->_components;
}
傳回一個值,指示定位器是否具有指定的組件定義或已實例化組件。
此方法可能會根據 $checkInstance
的值傳回不同的結果。
- 如果
$checkInstance
為 false (預設值),此方法將傳回值,指出定位器是否具有指定的元件定義。 - 如果
$checkInstance
為 true,此方法將傳回值,指出定位器是否已實例化指定的元件。
另請參閱 set()。
public boolean has ( $id, $checkInstance = false ) | ||
$id | string |
元件 ID (例如 |
$checkInstance | boolean |
此方法是否應檢查元件是否為共用且已實例化。 |
return | boolean |
定位器是否具有指定的元件定義,或是否已實例化元件。 |
---|
public function has($id, $checkInstance = false)
{
return $checkInstance ? isset($this->_components[$id]) : isset($this->_definitions[$id]);
}
Defined in: yii\base\Component::hasEventHandlers()
傳回值,指出是否有任何處理常式附加到具名的事件。
public boolean hasEventHandlers ( $name ) | ||
$name | string |
事件名稱 |
return | boolean |
是否有任何處理常式附加到事件。 |
---|
public function hasEventHandlers($name)
{
$this->ensureBehaviors();
if (!empty($this->_events[$name])) {
return true;
}
foreach ($this->_eventWildcards as $wildcard => $handlers) {
if (!empty($handlers) && StringHelper::matchWildcard($wildcard, $name)) {
return true;
}
}
return Event::hasHandlers($this, $name);
}
Defined in: yii\base\Component::hasMethod()
傳回值,指出是否已定義方法。
如果符合以下條件,則定義方法
- 類別具有具有指定名稱的方法
- 附加的行為具有給定名稱的方法 (當
$checkBehaviors
為 true 時)。
public boolean hasMethod ( $name, $checkBehaviors = true ) | ||
$name | string |
屬性名稱 |
$checkBehaviors | boolean |
是否將行為的方法視為此元件的方法 |
return | boolean |
是否已定義方法 |
---|
public function hasMethod($name, $checkBehaviors = true)
{
if (method_exists($this, $name)) {
return true;
} elseif ($checkBehaviors) {
$this->ensureBehaviors();
foreach ($this->_behaviors as $behavior) {
if ($behavior->hasMethod($name)) {
return true;
}
}
}
return false;
}
Defined in: yii\base\Component::hasProperty()
傳回值,指出是否已為此元件定義屬性。
如果符合以下條件,則定義屬性
- 類別具有與指定名稱相關聯的 getter 或 setter 方法 (在此情況下,屬性名稱不區分大小寫);
- 類別具有具有指定名稱的成員變數 (當
$checkVars
為 true 時); - 附加的行為具有給定名稱的屬性 (當
$checkBehaviors
為 true 時)。
另請參閱
public boolean hasProperty ( $name, $checkVars = true, $checkBehaviors = true ) | ||
$name | string |
屬性名稱 |
$checkVars | boolean |
是否將成員變數視為屬性 |
$checkBehaviors | boolean |
是否將行為的屬性視為此元件的屬性 |
return | boolean |
是否已定義屬性 |
---|
public function hasProperty($name, $checkVars = true, $checkBehaviors = true)
{
return $this->canGetProperty($name, $checkVars, $checkBehaviors) || $this->canSetProperty($name, false, $checkBehaviors);
}
public void init ( ) |
public function init()
{
}
Defined in: yii\base\Component::off()
從此元件卸離現有的事件處理常式。
此方法與 on() 相反。
注意:如果為事件名稱傳遞萬用字元模式,則只會移除使用此萬用字元註冊的處理常式,而使用符合此萬用字元的純名稱註冊的處理常式將會保留。
另請參閱 on()。
public boolean off ( $name, $handler = null ) | ||
$name | string |
事件名稱 |
$handler | callable|null |
要移除的事件處理器。如果為 null,則會移除附加到指定事件名稱的所有處理器。 |
return | boolean |
如果找到並分離處理器 |
---|
public function off($name, $handler = null)
{
$this->ensureBehaviors();
if (empty($this->_events[$name]) && empty($this->_eventWildcards[$name])) {
return false;
}
if ($handler === null) {
unset($this->_events[$name], $this->_eventWildcards[$name]);
return true;
}
$removed = false;
// plain event names
if (isset($this->_events[$name])) {
foreach ($this->_events[$name] as $i => $event) {
if ($event[0] === $handler) {
unset($this->_events[$name][$i]);
$removed = true;
}
}
if ($removed) {
$this->_events[$name] = array_values($this->_events[$name]);
return true;
}
}
// wildcard event names
if (isset($this->_eventWildcards[$name])) {
foreach ($this->_eventWildcards[$name] as $i => $event) {
if ($event[0] === $handler) {
unset($this->_eventWildcards[$name][$i]);
$removed = true;
}
}
if ($removed) {
$this->_eventWildcards[$name] = array_values($this->_eventWildcards[$name]);
// remove empty wildcards to save future redundant regex checks:
if (empty($this->_eventWildcards[$name])) {
unset($this->_eventWildcards[$name]);
}
}
}
return $removed;
}
將事件處理常式附加到事件。
事件處理器必須是有效的 PHP 回呼。以下是一些範例
function ($event) { ... } // anonymous function
[$object, 'handleClick'] // $object->handleClick()
['Page', 'handleClick'] // Page::handleClick()
'handleClick' // global function handleClick()
事件處理器必須使用以下簽名來定義,
function ($event)
其中 $event
是一個 yii\base\Event 物件,其中包含與事件相關聯的參數。
自 2.0.14 版本起,您可以將事件名稱指定為萬用字元模式
$component->on('event.group.*', function ($event) {
Yii::trace($event->name . ' is triggered.');
});
另請參閱 off()。
public void on ( $name, $handler, $data = null, $append = true ) | ||
$name | string |
事件名稱 |
$handler | 可呼叫 (callable) |
事件處理器 |
$data | mixed |
當事件被觸發時,要傳遞給事件處理器的資料。當事件處理器被調用時,可以透過 yii\base\Event::$data 存取此資料。 |
$append | boolean |
是否將新的事件處理器附加到現有處理器列表的末尾。如果為 false,新的處理器將會插入到現有處理器列表的開頭。 |
public function on($name, $handler, $data = null, $append = true)
{
$this->ensureBehaviors();
if (strpos($name, '*') !== false) {
if ($append || empty($this->_eventWildcards[$name])) {
$this->_eventWildcards[$name][] = [$handler, $data];
} else {
array_unshift($this->_eventWildcards[$name], [$handler, $data]);
}
return;
}
if ($append || empty($this->_events[$name])) {
$this->_events[$name][] = [$handler, $data];
} else {
array_unshift($this->_events[$name], [$handler, $data]);
}
}
向此定位器註冊元件定義。
例如:
// a class name
$locator->set('cache', 'yii\caching\FileCache');
// a configuration array
$locator->set('db', [
'class' => 'yii\db\Connection',
'dsn' => 'mysql:host=127.0.0.1;dbname=demo',
'username' => 'root',
'password' => '',
'charset' => 'utf8',
]);
// an anonymous function
$locator->set('cache', function ($params) {
return new \yii\caching\FileCache;
});
// an instance
$locator->set('cache', new \yii\caching\FileCache);
如果具有相同 ID 的組件定義已存在,它將會被覆寫。
public void set ( $id, $definition ) | ||
$id | string |
元件 ID (例如 |
$definition | mixed |
要向此定位器註冊的組件定義。它可以是下列其中之一 |
throws | yii\base\InvalidConfigException |
如果定義是無效的組態陣列 |
---|
public function set($id, $definition)
{
unset($this->_components[$id]);
if ($definition === null) {
unset($this->_definitions[$id]);
return;
}
if (is_object($definition) || is_callable($definition, true)) {
// an object, a class name, or a PHP callable
$this->_definitions[$id] = $definition;
} elseif (is_array($definition)) {
// a configuration array
if (isset($definition['__class'])) {
$this->_definitions[$id] = $definition;
$this->_definitions[$id]['class'] = $definition['__class'];
unset($this->_definitions[$id]['__class']);
} elseif (isset($definition['class'])) {
$this->_definitions[$id] = $definition;
} else {
throw new InvalidConfigException("The configuration for the \"$id\" component must contain a \"class\" element.");
}
} else {
throw new InvalidConfigException("Unexpected configuration type for the \"$id\" component: " . gettype($definition));
}
}
在此定位器中註冊一組元件定義。
這是 set() 的批量版本。參數應該是一個陣列,其鍵為組件 ID,值為對應的組件定義。
有關如何指定組件 ID 和定義的更多詳細資訊,請參閱 set()。
如果具有相同 ID 的組件定義已存在,它將會被覆寫。
以下是註冊兩個組件定義的範例
[
'db' => [
'class' => 'yii\db\Connection',
'dsn' => 'sqlite:path/to/file.db',
],
'cache' => [
'class' => 'yii\caching\DbCache',
'db' => 'db',
],
]
public void setComponents ( $components ) | ||
$components | array |
組件定義或實例 |
public function setComponents($components)
{
foreach ($components as $id => $component) {
$this->set($id, $component);
}
}
public void trigger ( $name, yii\base\Event $event = null ) | ||
$name | string |
事件名稱 |
$event | yii\base\Event|null |
事件實例。如果未設定,將會建立預設的 yii\base\Event 物件。 |
public function trigger($name, Event $event = null)
{
$this->ensureBehaviors();
$eventHandlers = [];
foreach ($this->_eventWildcards as $wildcard => $handlers) {
if (StringHelper::matchWildcard($wildcard, $name)) {
$eventHandlers[] = $handlers;
}
}
if (!empty($this->_events[$name])) {
$eventHandlers[] = $this->_events[$name];
}
if (!empty($eventHandlers)) {
$eventHandlers = call_user_func_array('array_merge', $eventHandlers);
if ($event === null) {
$event = new Event();
}
if ($event->sender === null) {
$event->sender = $this;
}
$event->handled = false;
$event->name = $name;
foreach ($eventHandlers as $handler) {
$event->data = $handler[1];
call_user_func($handler[0], $event);
// stop further handling if the event is handled
if ($event->handled) {
return;
}
}
}
// invoke class-level attached handlers
Event::trigger($this, $name, $event);
}
註冊 或 登入 以發表評論。