php - 静态类“非静态方法”错误中的 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
}
}
帮助表示赞赏!
解决方案
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 在评论中指出的那样,外观也可以工作,但“技巧”大致相同。
推荐阅读
- c - 是否可以在堆栈上分配结构,其定义隐藏在源文件中?
- android - 当我滚动或添加新项目时,RecyclerView 数据移动到其他项目
- ruby-on-rails - 如何在 Ruby 中添加带有条件的模型验证
- c++ - 在哪里放置指针?
- c++ - C ++使用命名空间到嵌套的相同命名空间中
- r - 编织到 pdf 时包裹在 knitr 块中生成的图形
- c - 这是“反转”字节的正确方法吗?(按位非)
- windows - 使用 .NET 或通过安装程序更改 Windows 机器上的组策略
- python - 如何规范seaborn distplot?
- ruby-on-rails - 在 Rails 中按路径生成页面标题