在 Laravel 中的何处使用事件记录器控制器
Where to use Event Logger Controller in Laravel
我创建了一个事件控制器来记录对我的 API 的所有请求。我知道在其他控制器中使用控制器不是一个好主意,所以...我必须在哪里实现它?
事件控制器:
<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use App\Event;
class EventController extends Controller
{
protected static $instance = null;
/** call this method to get instance */
public static function instance(){
if (static::$instance === null){
static::$instance = new static();
}
return static::$instance;
}
/** protected to prevent cloning */
protected function __clone(){
}
/** protected to prevent instantiation from outside of the class */
protected function __construct(){
}
public function create($type, $description){
Event::create([
'id_type' => $type,
'date_time' => date('Y-m-d H:i:s'),
'id_users' => auth()->user()->id,
'description' => $description
]);
}
}
我建议的2种方式:
1.make 一个 event
并在所有操作中触发它。
2.make a middleware
并将其添加到您的每个路由中(或添加到路由组中)
第二个是better.because中间件,正是为此reason.All发送到服务器的请求应该首先通过中间件。
在 brief:you 中应该使用 php artisan make:middleware yourMiddlewareName
创建中间件,并在其中添加控制器代码后,您应该在中间件数组的 kernel.php 中添加此中间件的名称。
现在它已准备好为您想要的每条路线分配它,方法是在末尾附加 ->middleware("yourMiddlewareName")
if each one.
我创建了一个事件控制器来记录对我的 API 的所有请求。我知道在其他控制器中使用控制器不是一个好主意,所以...我必须在哪里实现它?
事件控制器:
<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use App\Event;
class EventController extends Controller
{
protected static $instance = null;
/** call this method to get instance */
public static function instance(){
if (static::$instance === null){
static::$instance = new static();
}
return static::$instance;
}
/** protected to prevent cloning */
protected function __clone(){
}
/** protected to prevent instantiation from outside of the class */
protected function __construct(){
}
public function create($type, $description){
Event::create([
'id_type' => $type,
'date_time' => date('Y-m-d H:i:s'),
'id_users' => auth()->user()->id,
'description' => $description
]);
}
}
我建议的2种方式:
1.make 一个 event
并在所有操作中触发它。
2.make a middleware
并将其添加到您的每个路由中(或添加到路由组中)
第二个是better.because中间件,正是为此reason.All发送到服务器的请求应该首先通过中间件。
在 brief:you 中应该使用 php artisan make:middleware yourMiddlewareName
创建中间件,并在其中添加控制器代码后,您应该在中间件数组的 kernel.php 中添加此中间件的名称。
现在它已准备好为您想要的每条路线分配它,方法是在末尾附加 ->middleware("yourMiddlewareName")
if each one.