【问题标题】:Where to use Event Logger Controller in LaravelLaravel 在哪里使用事件记录器控制器
【发布时间】:2020-02-09 20:46:27
【问题描述】:

我创建了一个事件控制器来记录对我的 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       
        ]);
    }
}

【问题讨论】:

  • 为什么不用中间件并申请每条路由?
  • 您可以创建一个特征并在任何地方使用它(在控制器、中间件等中)。检查我为记录所做的这个要点:gist.github.com/qumberrizvi/f43933521a3d1aec11d4bf10d49675b2
  • @ka_lin 这可能是一种选择。
  • @QumberRizvi 我会看的

标签: laravel laravel-6 laravel-6.2


【解决方案1】:

我建议的两种方式:

1.创建一个event 并在所有操作中触发它。 2.制作一个middleware并将其添加到您的每个路由中(或添加到路由组中)

第二个更好。因为中间件正是出于这个原因。所有发送到服务器的请求都应该首先通过中间件。 简而言之:您应该使用php artisan make:middleware yourMiddlewareName 创建中间件,并在其中添加控制器代码后,您应该在中间件数组的 kernel.php 中添加此中间件的名称。 现在它已准备好为您想要的每条路线分配它,如果每条路线最后都附加-&gt;middleware("yourMiddlewareName")

【讨论】:

    猜你喜欢
    • 2018-03-29
    • 1970-01-01
    • 2014-07-16
    • 1970-01-01
    • 2014-09-22
    • 2015-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多