为门面导入命名空间的正确方法是什么(例如Hash::make
)?
我是否需要像 use Illuminate\Support\Facades\Hash
那样使用导入?
我看到有些人将它们用作 \Hash::make
(来自命名空间文件,例如默认创建的 Controller )或 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);
}
但我不明白为什么如果这个类在 Illuminate\Support\Facades\
命名空间中,而不是在根命名空间中,它为什么会起作用。
最佳答案
您正在将外观与别名进行比较。
Illuminate\Support\Facades\Hash
是一个外观类,而 \Hash
是该外观的别名类。查看您的 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
外观类;两者都是正确的。
在引导阶段,Laravel 使用名为 AliasLoader
的服务。 .它从 config/app.php
获取别名数组,迭代所有元素,并使用 PHP 的 spl_autoload_register
创建一个 __autoload
函数队列.
每个 __autoload
函数负责使用 PHP 的 class_alias
为各自的外观类创建别名。功能。因此,我们不必在使用类之前导入类和别名。
阅读更多:
How Laravel Facades Work and How to Use Them Elsewhere
关于php - 使用/导入 Laravel facades 的正确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40703341/