概念
類的別名
註冊的型別別名protected $aliases = [];
以抽象名稱為鍵的已註冊別名protected $abstractAliases = [];
原始碼
class Application >
public function __construct($basePath = null)
{
// 在容器中註冊核心(core)類別名
$this->registerCoreContainerAliases();
}
---------------------------------------------------------------------------
public function registerCoreContainerAliases()
{
foreach ([
'app'=> [self::class, \Illuminate\Contracts\Container\Container::class, \Illuminate\Contracts\Foundation\Application::class, \Psr\Container\ContainerInterface::class],
'auth' => [\Illuminate\Auth\AuthManager::class, \Illuminate\Contracts\Auth\Factory::class],
...
] as $key => $aliases) {
foreach ($aliases as $alias) {
$this->alias($key, $alias);
}
}
}
--------------------------------------------------------------------------
class Container >
public function alias($abstract, $alias)
{
$this->aliases[$alias] = $abstract;
$this->abstractAliases[$abstract][] = $alias;
}
---------------------------------------------------------------------------
列印後
--------------------------------------------------------------------
#aliases: array:64 [
"Illuminate\Foundation\Application" => "app"
"Illuminate\Contracts\Container\Container" => "app"
"Illuminate\Contracts\Foundation\Application" => "app"
"Psr\Container\ContainerInterface" => "app"
"Illuminate\Auth\AuthManager" => "auth"
"Illuminate\Contracts\Auth\Factory" => "auth"
...
]
-------------------------------------------------------------------
#abstractAliases: array:34 [
"app" => array:4 [
0 => "Illuminate\Foundation\Application"
1 => "Illuminate\Contracts\Container\Container"
2 => "Illuminate\Contracts\Foundation\Application"
3 => "Psr\Container\ContainerInterface"
]
"auth" => array:2 [
0 => "Illuminate\Auth\AuthManager"
1 => "Illuminate\Contracts\Auth\Factory"
]
...
]
--------------------------------------------------------------------
總結
alias()
相對簡單,通過這個方法的原始碼,可發現幾個特點:
- 屬性
$aliases
與屬性$abstractAliases
是鍵值對相反的,是互相對應的。 $aliases
中可以通過實現類以及它所實現的契約類任何一個找到相同的別名。反之,在$abtractAliases
中通過別名可找到類名及它所實現的契約類。
本作品採用《CC 協議》,轉載必須註明作者和本文連結