use/import Laravel 立面的正确方法是什么?
What is the correct way to use/import Laravel facades?
为门面(例如Hash::make
)导入命名空间的正确方法是什么?
我需要像 use Illuminate\Support\Facades\Hash
一样使用导入吗?
我看到有些人将它们用作 \Hash::make
(来自命名空间文件,例如默认创建的控制器)或 Hash::make
(来自非命名空间文件,例如路由)。
同时 ide-helper 在根命名空间中生成外观:
namespace {
exit("This file should not be included, only analyzed by your IDE");
class Hash extends \Illuminate\Support\Facades\Hash{
/** ... */
public static function make($value, $options = array()){
return \Illuminate\Hashing\BcryptHasher::make($value, $options);
}
但我不明白如果这个 class 在 Illuminate\Support\Facades\
命名空间中,而不是在根命名空间中,为什么它会起作用。
在您的 config/app.php
文件中,您可以看到 aliases
的列表。 Hash
包含在那里,因此您只需使用 use Hash;
即可导入 Hash
\Hash::make
,这里的\
是指从根命名空间。因此,您可以使用 use Hash
在顶部导入 Hash
或直接使用 \Hash::make
您正在将外观与别名进行比较。
Illuminate\Support\Facades\Hash
是外观 class,但 \Hash
是该外观的别名 class。查看您的 config/app.php
并查看它们的映射方式:
'aliases' => [
'App' => Illuminate\Support\Facades\App::class,
'Artisan' => Illuminate\Support\Facades\Artisan::class,
'Auth' => Illuminate\Support\Facades\Auth::class,
// ...
您可以使用 \Hash
别名或 Illuminate\Support\Facades\Hash
外观 class;都是正确的。
在引导阶段,Laravel 使用名为 AliasLoader
的服务。它从 config/app.php
获取别名数组,遍历所有元素,并使用 PHP 的 spl_autoload_register
创建一个 __autoload
函数队列。
每个 __autoload
函数负责使用 PHP 的 class_alias
函数为各自的外观 class 创建别名。因此,我们在使用 class 之前不必导入和别名。
阅读更多:
How Laravel Facades Work and How to Use Them Elsewhere
为门面(例如Hash::make
)导入命名空间的正确方法是什么?
我需要像 use Illuminate\Support\Facades\Hash
一样使用导入吗?
我看到有些人将它们用作 \Hash::make
(来自命名空间文件,例如默认创建的控制器)或 Hash::make
(来自非命名空间文件,例如路由)。
同时 ide-helper 在根命名空间中生成外观:
namespace {
exit("This file should not be included, only analyzed by your IDE");
class Hash extends \Illuminate\Support\Facades\Hash{
/** ... */
public static function make($value, $options = array()){
return \Illuminate\Hashing\BcryptHasher::make($value, $options);
}
但我不明白如果这个 class 在 Illuminate\Support\Facades\
命名空间中,而不是在根命名空间中,为什么它会起作用。
在您的 config/app.php
文件中,您可以看到 aliases
的列表。 Hash
包含在那里,因此您只需使用 use Hash;
Hash
\Hash::make
,这里的\
是指从根命名空间。因此,您可以使用 use Hash
在顶部导入 Hash
或直接使用 \Hash::make
您正在将外观与别名进行比较。
Illuminate\Support\Facades\Hash
是外观 class,但 \Hash
是该外观的别名 class。查看您的 config/app.php
并查看它们的映射方式:
'aliases' => [
'App' => Illuminate\Support\Facades\App::class,
'Artisan' => Illuminate\Support\Facades\Artisan::class,
'Auth' => Illuminate\Support\Facades\Auth::class,
// ...
您可以使用 \Hash
别名或 Illuminate\Support\Facades\Hash
外观 class;都是正确的。
在引导阶段,Laravel 使用名为 AliasLoader
的服务。它从 config/app.php
获取别名数组,遍历所有元素,并使用 PHP 的 spl_autoload_register
创建一个 __autoload
函数队列。
每个 __autoload
函数负责使用 PHP 的 class_alias
函数为各自的外观 class 创建别名。因此,我们在使用 class 之前不必导入和别名。
阅读更多:
How Laravel Facades Work and How to Use Them Elsewhere