夏期劇*_*期劇場 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)
我错过了什么,或者我该如何解决这个问题?
谢谢你们.
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)
| 归档时间: |
|
| 查看次数: |
5225 次 |
| 最近记录: |