【问题标题】:How to get underlying class name from Facade name in Laravel如何从 Laravel 中的外观名称获取底层类名称
【发布时间】:2017-09-12 09:49:02
【问题描述】:

我发现理解 Facades 有点困难。特别是如何从外观名称中找到底层类名称/位置。我已经浏览了文档,但仍然不清楚。例如,当使用Auth::login() ,我发现 Auth 门面中没有login() 方法。

 class Auth extends Facade
{
/**
 * Get the registered name of the component.
 *
 * @return string
 */
protected static function getFacadeAccessor()
{
    return 'auth';
}

/**
 * Register the typical authentication routes for an application.
 *
 * @return void
 */
 public static function routes()
 {
    static::$app->make('router')->auth();
 }
}

Auth门面getFacadeAccessor()方法返回一个字符串auth。但是我应该看哪个auth 类?如何解析实际类?

谢谢,

【问题讨论】:

标签: laravel laravel-facade


【解决方案1】:

您可以使用getFacadeRoot()

例如

$object = Auth::getFacadeRoot() // Illuminate\Auth\AuthManager instance

或获取完全限定的类名

$class = get_class(Auth::getFacadeRoot()) // 'Illuminate\Auth\AuthManager'

您也可以使用容器通过它的访问器来解析一个类。这就是 Laravel 在解析 Facade 时所做的事情。

$object = resolve('auth'); // Illuminate\Auth\AuthManager instance

【讨论】:

    【解决方案2】:

    在 Serviceprovider 的某个地方,auth 密钥被注册到某个东西。对于vendor/laravel/frameworksrc/Illuminate/Auth/AuthServiceProvider.php 中的auth 键。可以看到在registerAuthenticator()方法中,auth键以单例模式注册到Illuminate\Auth\AuthManager

    容器有多种方法可以将键绑定到特定类。例如bindsingleton 之类的方法。 Facades 只是一个额外的类,用于从根命名空间静态调用主类。

    如果要查看使用了哪个类,可以使用以下代码:get_class(resolve('auth'))。当然,您可以将 auth 替换为您想要检查的任何字符串。

    奖励:我认为您可以通过以某种方式注册自己的经理来覆盖此行为。我建议您扩展普通的 AuthManager 并覆盖您希望更改的方法。

    【讨论】:

    • 嗨,马克。应用程序如何知道要解析“应用程序”,它必须转到 Illuminate/Auth/AuthServiceProvider.php 类?
    • 您在config/app.php 文件中注册了AuthServiceProvider。如果你在那里注册它,它将在启动时执行bootregister方法。
    【解决方案3】:

    一种选择是在外观上使用@see 注释

    /**
     * @see \Illuminate\Auth\AuthManager
     * @see \Illuminate\Contracts\Auth\Factory
     * @see \Illuminate\Contracts\Auth\Guard
     * @see \Illuminate\Contracts\Auth\StatefulGuard
     */
    class Auth extends Facade
    

    通常该方法应该存在于这些类/接口上

    例如,Auth::check() 存在于\Illuminate\Contracts\Auth\Guard::check()

    如果您使用允许您遵循这些定义的编辑器,则遍历起来会更容易一些。通常只有一个 @see 注释,因此很容易找到该类。

    【讨论】:

    • 嗨变形。是的,sublime text 有这个功能。但我想学习如何自己解决这个问题。不过还是谢谢。
    【解决方案4】:

    您可以在包/服务上使用getFacadeRoot() 来获取其对象:

    例如,我编写了一个辅助函数来获取Facade 对象,这样我就可以在任何地方轻松使用该Cart 对象:

    function cart() {
        return \Gloudemans\Shoppingcart\Facades\Cart::getFacadeRoot();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-12-24
      • 2019-08-27
      • 2013-12-23
      • 1970-01-01
      • 2016-07-30
      • 2023-03-13
      • 2017-10-14
      相关资源
      最近更新 更多