【问题标题】:Laravel: Cannot access protected function of FacadeLaravel:无法访问 Facade 的受保护功能
【发布时间】:2021-05-11 11:19:44
【问题描述】:

我想通过扩展Facades\Auth来重写Illuminate\Auth\SessionGuardonceBasic(),但是遇到无法访问SessionGuard类的helper protected函数的问题。 以下是我扩展 Auth 外观的方式:

namespace App\MyFacades;
use \Illuminate\Support\Facades\Auth;

class Auth_QuyLe extends Auth {

        /**
         * Create your custom methods here...
         */
        public static function onceBasic_QuyLe($field = 'name', $extraConditions = [])
        {   
            $credentials =  self::basicCredentials(self::getRequest(), $field);

            if (! self::once(array_merge($credentials, $extraConditions))) {
                return self::failedBasicResponse();
            }
        }

}

当我从中间件调用 onceBasic_QuyLe() 时,它会显示

"Method Illuminate\Auth\SessionGuard::basicCredentials does not exist."

我已经将我的课程更新为 config/app.php 并运行 composer dump-autoload && php artisan config:cache

【问题讨论】:

  • 不要尝试对 Facade 进行任何更改。 Facades 只是解析底层类的一个实例,在这种情况下是当前使用的 Auth 保护 (SessionGuard)。
  • 不...我不更改外观...我不修改 laraval 核心的单个代码...我所做的是“扩展它”,创建自己的功能,利用来自 Auth Facades 的一些助手...这里有一些类似的帖子 SO:stackoverflow.com/questions/40614875/laravel-5-extend-a-facade | stackoverflow.com/questions/16953460/… | stackoverflow.com/questions/52944843/… 我不知道为什么在我的情况下,我无法访问 Auth 门面的受保护功能,尽管公共功能很好......
  • 抱歉,我并不是要建议您在核心中编辑任何内容。我的意思是扩展外观本身并不是答案。在大多数情况下,将 Facade 视为辅助功能,例如auth()->user()Auth::user() 将调用相同的方法,因为它们实际上将调用委托给底层 Guard 类。实际上,您需要扩展底层的 Guard 类并让 Laravel 使用它。
  • 不管怎样,你用的是什么版本的 Laravel?
  • 好的...感谢您的建议...我刚刚尝试扩展底层 Guard 类:<?php class Auth_QuyLe extends SessionGuard { ... } 但它仍然显示相同的错误"Method Illuminate\Auth\SessionGuard::onceBasic_QuyLe does not exist",这意味着他们无法访问扩展的我刚刚添加的函数(onceBasic_QuyLe())。我正在使用 Laravel 5.8

标签: php laravel


【解决方案1】:

我终于找到了解决办法:

首先,b/c SessionGuard 是一个“可宏”类,如果你需要在SessionGuard 中添加额外的方法,你需要去AppServiceProvider 并在服务提供者的启动方法中声明宏

public function boot()
    {
        SessionGuard::macro('myOnceBasic', function ($field = 'name', $extraConditions = []) {

            $credentials = $this->basicCredentials($this->getRequest(), $field);

            if (!$this->once(array_merge($credentials, $extraConditions))) {
                return$this->failedBasicResponse();
            }
        });
}

并且在您新创建的 Facades 所代表的底层类中,您可以使用 Auth facade 来调用宏:

class MySessionGuard{

        public function myOnceBasic($field = 'name', $extraConditions = [])
        {   
            Auth::myOnceBasic($field = 'name', $extraConditions = []);
        }

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-09-13
    • 1970-01-01
    • 2020-01-20
    • 2015-01-30
    • 1970-01-01
    • 2016-08-27
    • 2011-01-02
    • 1970-01-01
    相关资源
    最近更新 更多