Laravel 5.2:如何从自己的事件侦听器访问请求和会话类?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36493760/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel 5.2 : How to access Request & Session Classes from own Event Listener?
提问by u775856
In Laravel 5.2
, i have added my Event Listener (into app\Providers\EventServiceProvider.php
), like:
在 中Laravel 5.2
,我添加了我的事件侦听器(到app\Providers\EventServiceProvider.php
),例如:
protected $listen = [
'Illuminate\Auth\Events\Login' => ['App\Listeners\UserLoggedIn'],
];
Then generated it:
然后生成它:
php artisan event:generate
Then in the Event Listener file itself app/Listeners/UserLoggedIn.php
, it's like:
然后在事件侦听器文件本身中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!');
}
}
This shows me following Errors:
这向我显示了以下错误:
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?
我错过了什么,或者我该如何解决这个问题?
- Ultimately, i need to write into Laravel Sessions once the User has logged in.
- 最终,我需要在用户登录后写入 Laravel Sessions。
Thank you all.
谢谢你们。
回答by Giedrius Kir?ys
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:
您正在尝试初始化,App\Listeners\Request;
但它应该是Illuminate\Http\Request
。这也可能不起作用,因此对于计划 B,请使用以下代码:
public function handle(Login $event)
{
app('request')->session()->put('test', 'hello world!');
}
Dependency Injection Update:
依赖注入更新:
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:
然后在handle
方法中您可以使用存储在构造函数中的本地请求变量:
public function handle(Login $event)
{
$this->request->session()->put('test', 'hello world!');
}