Laravel 5.2:如何访问请求和来自自己的事件侦听器的会话类? [英] Laravel 5.2 : How to access Request & Session Classes from own Event Listener?
问题描述
在 Laravel 5.2
中,我添加了我的事件监听器(到$ code> app \Providers\EventServiceProvider.php ),如:
In Laravel 5.2
, i have added my Event Listener (into app\Providers\EventServiceProvider.php
), like:
protected $listen = [
'Illuminate\Auth\Events\Login' => ['App\Listeners\UserLoggedIn'],
];
然后生成它:
php artisan event:generate
然后在事件监听器文件本身 app / Listeners / UserLoggedIn.php
,就像:
Then in the Event Listener file itself app/Listeners/UserLoggedIn.php
, it's like:
<?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!');
}
}
这显示了以下错误:
ErrorException in UserLoggedIn.php line 28:
Argument 2 passed to App\Listeners\UserLoggedIn::handle() must be an instance of App\Listeners\Request, none given
我想念了什么,解决这个问题吗?
What did i miss, or how can i solve this please?
- 最终,我需要在用户登录后写入Laravel会话。
谢谢大家。
推荐答案
您正在尝试初始化 App \Listeners\Request;
,但应该是 Illuminate\Http\Request
。另外这可能无效,所以对于计划B使用这个代码:
You are trying to initialize App\Listeners\Request;
but it should be Illuminate\Http\Request
. Also this might not work, so for plan B use this code:
public function handle(Login $event)
{
app('request')->session()->put('test', 'hello world!');
}
依赖注入更新:
如果要在事件中使用依赖注入,您应该通过构造函数注入类,如下所示:
If You want to use dependency injection in events, You should inject classes through constructor like so:
public function __construct(Request $request)
{
$this->request = $request;
}
然后在句柄
方法您可以使用存储在构造函数中的本地请求变量:
Then in handle
method You can use local request variable which was stored in constructor:
public function handle(Login $event)
{
$this->request->session()->put('test', 'hello world!');
}
这篇关于Laravel 5.2:如何访问请求和来自自己的事件侦听器的会话类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!