php - 向 Auth Class Laravel 添加自定义函数(扩展 Guard 类)

标签 php laravel laravel-5

我修改了放置在

的 Laravel 供应商文件

/vendor/laravel/framework/src/Illuminate/Auth/Guard.php

但它会在更新 Laravel 时被覆盖。

我正在寻找一种方法将代码放在我的/app 中的某处以防止覆盖。

修改的函数为

public function UpdateSession() {
    $this->session->set('type', $type); //==> Set Client Type
}

文件上还有一个新函数:

public function type() {
    return $this->session->get('type'); //==> Get Client Type
}

上面的代码在我的应用程序中的许多地方被调用。

有什么想法吗?

最佳答案

步骤:
1- 创建 myGuard.php

class myGuard extends Guard
{
    public function login(Authenticatable $user, $remember = false)
    {
        $this->updateSession($user->getAuthIdentifier(), $user->type);
        if ($remember) {
            $this->createRememberTokenIfDoesntExist($user);
            $this->queueRecallerCookie($user);
        }
        $this->fireLoginEvent($user, $remember);
        $this->setUser($user);
    }

    protected function updateSession($id, $type = null)
    {
        $this->session->set($this->getName(), $id);
        $this->session->set('type', $type);
        $this->session->migrate(true);
    }

    public function type()
    {
        return $this->session->get('type');
    }
}

2-在 AppServiceProvider 或新服务提供商或 routes.php 中:

public function boot()
{
    Auth::extend(
        'customAuth',
        function ($app) {
            $model = $app['config']['auth.model'];
            $provider = new EloquentUserProvider($app['hash'],    $model);
            return new myGuard($provider, App::make('session.store'));
        }
    );
}

3- 在 config/auth.php 中

'driver' => 'customAuth',

4- 现在你可以使用它了

Auth::type();

关于php - 向 Auth Class Laravel 添加自定义函数(扩展 Guard 类),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33368037/

相关文章:

php - phpunit 中未定义的 action()

php - 迭代表中的列表值

php - 我如何使用嵌套的急切加载和 Eloquent 和 laravel 来获取另一个表中的外键名称

php - 如何将大型对象/数组序列化为 JSON

php - 仅在唯一时插入(检查 2 行)

logging - Laravel 请求和响应日志记录

Laravel Mix 不发出 css

php - Laravel 5.1 - 自定义验证语言文件

jQuery 单击一个按钮最终单击具有相同类的所有按钮

javascript - 如何在照片删除后重定向到模式 - Laravel