Laravel 5.2:如何从自己的事件监听器访问请求和会话类?

夏期劇*_*期劇場 3 session event-handling http-request laravel laravel-5.2

Laravel 5.2,我添加了我的事件监听器(入app\Providers\EventServiceProvider.php),如:

protected $listen = [
  'Illuminate\Auth\Events\Login' => ['App\Listeners\UserLoggedIn'],
];
Run Code Online (Sandbox Code Playgroud)

然后生成它:

php artisan event:generate
Run Code Online (Sandbox Code Playgroud)

然后在Event Listener文件中app/Listeners/UserLoggedIn.php,它就像:

<?php

namespace App\Listeners;

use App\Listeners\Request;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Auth\Events\Login;

class UserLoggedIn
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {

    }

    /**
     * Handle the event.
     *
     * @param  Login  $event
     * @return void
     */
    public function handle(Login $event, Request $request)
    {
        $request->session()->put('test', 'hello world!');
    }
}
Run Code Online (Sandbox Code Playgroud)

这告诉我以下错误:

ErrorException in UserLoggedIn.php line 28:
Argument 2 passed to App\Listeners\UserLoggedIn::handle() must be an instance of App\Listeners\Request, none given
Run Code Online (Sandbox Code Playgroud)

我错过了什么,或者我该如何解决这个问题?

  • 最终,我需要在用户登录后写入Laravel Sessions.

谢谢你们.

Gie*_*šys 12

您正在尝试初始化App\Listeners\Request;但应该是Illuminate\Http\Request.这也可能不起作用,因此对于B计划使用此代码:

public function handle(Login $event)
{
    app('request')->session()->put('test', 'hello world!');
}
Run Code Online (Sandbox Code Playgroud)

依赖注入更新:

如果你想在事件中使用依赖注入,你应该通过构造函数注入类,如下所示:

public function __construct(Request $request)
{
    $this->request = $request;
}
Run Code Online (Sandbox Code Playgroud)

然后在handle方法中您可以使用存储在构造函数中的本地请求变量:

public function handle(Login $event)
{
    $this->request->session()->put('test', 'hello world!');
}
Run Code Online (Sandbox Code Playgroud)

  • 这是依赖注入的例子。这是一个非常广泛的话题,但我可以说 - 你可以使用它。您可以在此处阅读更多相关信息:https://laravel.com/docs/master/container#introduction。在事件处理程序中,如果你想使用依赖注入,你必须像这样在构造函数方法中使用它:`public function __construct(Request $request)`,然后将该对象保存到类变量中。之后,您将能够在 `handle` 方法中使用它。抱歉造成混乱,但依赖注入是一件很难解释的事情:) (2认同)
  • 这取决于。:) 但在我看来,依赖注入是更干净的解决方案。 (2认同)