首页 > 解决方案 > 静态类“非静态方法”错误中的 Laravel Auth

问题描述

我正在制作在一个文件中处理无聊的身份验证内容的课程。
但是我在这里调用身份验证函数时遇到了小问题。

我遇到的第一个问题是这个函数:

hasTooManyLoginAttempts

代码

if ($this->hasTooManyLoginAttempts($request)) {

触发错误:

Using $this when not in object context

当我将 $this-> 更改为 self::

if (self::hasTooManyLoginAttempts($request)) {

触发器

Non-static method My\AuthClass::hasTooManyLoginAttempts() should not be called statically

我正在尝试使用的示例类

namespace My\AuthClass;

use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Support\Facades\Auth;

class AuthClass
{
    use AuthenticatesUsers;

    public static function doLogin(Request $request)
    {
        // Validate login

        // Has too many login attempts?

        if (self::hasTooManyLoginAttempts($request)) {
            self::fireLockoutEvent($request);
            return redirect()->route('login.show')->with('error', 'You have tried to login too many times in short amount of time. Please try again later.');
        }

        // Try authenticate

        // Send login error
    }
}

帮助表示赞赏!

标签: phplaravellaravel-5.6

解决方案


public static function doLogin(Request $request)显然是一个静态函数,而hasTooManyLoginAttempts不是。

您不能使用双冒号调用它,也不能$this在静态上下文中使用。相当的困境。

您必须创建一种解决方法:

class AuthClass
{
  use AuthenticatesUsers;

  private static $instance = null;

  public static function doLogin(Request $request)
  {
    // Validate login

    $self = self::init();

    // Has too many login attempts?
    if ($self->hasTooManyLoginAttempts($request)) {
      $self->fireLockoutEvent($request);
      return redirect()->route('login.show')->with('error', 'You have tried to login too many times in short amount of time. Please try again later.');
    }

    // Try authenticate

    // Send login error
  }

  public static function init() {
    if(null === self::$instance) {
      self::$instance = new self;
    }

    return self::$instance;
  }
}

这里重要的部分是新init()功能(您可以随意命名)。它将创建当前类的新实例并允许您->在“静态”上下文中使用(它不是真正的静态)。


正如用户 Tuim 在评论中指出的那样,外观也可以工作,但“技巧”大致相同。


推荐阅读