我想实现一个用户跟踪系统,经过搜索我意识到我必须在中间件中做到这一点.我遇到的问题是,我只能在中间件中的答案中向响应头添加值.保存它们的信息后,在中间件响应中删除它们.请指导我如何在中间件响应中添加自定义数据,谢谢

为此,我找到了两个在json模式下工作的示例,但是在我想要将用户转移到路由的情况下,我必须使用头.

Json响应的示例代码:

return $response->json([
                    'status' => $status,
                    'code' => $code,
                    'errors' => [$errors],
                ], $status);

推荐答案

我在我的项目中做了完全相同的系统,没有使用头文件,请参见下面的示例

例如: 我们计划在软件中 for each 用户的表现创建一个跟踪系统,以便将其报告存储在系统中.

迁移:

Schema::create('user_trackings', function (Blueprint $table) {
            $table->id();
            $table->boolean('transaction')->default(1);
            $table->string('event');
            $table->string('class');
            $table->longText('request_params')->nullable();
            $table->string('request_method');
            $table->string('request_ip');
            $table->string('request_userAgent');
            $table->longText('params')->nullable();
            $table->foreignId('user_id')->constrained()->onUpdate('cascade')->onDelete('cascade');
            $table->timestamps();
            $table->softDeletes();
        });

♪角色控制器♪

use App\Traits\Response;

class RoleController extends Controller
{
    use Response;

    public function store(Request $request)
    {
        $Validator = Validator::make($request->all(), [
            'display_name' => ['required', 'unique:roles,display_name', 'max:255'],
            'name' => ['required', 'unique:roles,name', 'persian_not_accept', 'max:255'],
            'permissions' => ['nullable', "array","min:1"],
            'permissions.*' => ['nullable', 'exists:permissions,name'],
            'parent' => [new ParentRule('roles,name')]
        ]);
        if ($Validator->fails()) {
            $this->Validation($Validator);
            return back();
        }

        DB::beginTransaction();
        try {
            $Role = Role::create([
                'name' => $request->name,
                'display_name' => $request->display_name
            ]);
            $Role->syncPermissions($request->permissions);
            if($request->parent != 'no-parent'){
                $RoleParent = Role::findByName($request->parent);
                $Role->parent()->associate($RoleParent);
                $Role->save();
            }

            DB::commit();
        } catch (\Exception $e) {
            DB::rollback();
            $this->Error([
                'Permission' => $Role,
                'Exception' => $e->getMessage()
            ]);
        }
        return $this->Success([
            'Permission' => $Role
        ], 'role.index');
    }

}

响应式列车:

trait Response {
    use SweetAlert;

    public function Success($Params = [], $Route = null , $RouteParams = [], $title = null, $message = null){
        $title = is_null($title) ? __('message.response.title.Success') : $title;
        $message = is_null($message) ? __('message.response.message.Success') : $message;

        if($Route){
            return (new RedirectResponse(route($Route, $RouteParams)))->bag(true, $Params);
        }

        return (new HttpResponse)->json(['status' => true, 'message' => $message])->bag(true, $Params);
    }

    public function Error($Params = [], $Route = null , $RouteParams = [], $title = null, $message = null){
        $title = is_null($title) ? __('message.response.title.Error') : $title;
        $message = is_null($message) ? __('message.response.message.Error') : $message;

        if($Route){
            $this->AlertError( $title , $message );
            return (new RedirectResponse(route($Route, $RouteParams)))->bag(false, $Params);
        }

        return (new HttpResponse)->json(['status' => false, 'message' => $message])->bag(false, $Params);
    }

}

提示: 在中间件响应中,您将收到2种类型的响应,它们由2个类组成(Illuminate\Http\Response,Illuminate\Http\RedirectResponse),因此我们必须为此创建2个自定义类并扩展这2个类.

创建自定义响应:

1-1级:

namespace App\Library\Response;

use Illuminate\Http\RedirectResponse as BaseRedirectResponse;

class RedirectResponse extends BaseRedirectResponse {

    public $bag;

    public function bag($Status = null, $Data = null){
        $this->bag = (object) [
            'Status' => $Status,
            'Data' => $Data
        ];
        return $this;
    }
}

2--2级:

namespace App\Library\Response;

use Illuminate\Http\Response;

class HttpResponse extends Response {

    public $bag;

    public function bag($Status = null, $Data = null){
        $this->bag = (object) [
            'Status' => $Status,
            'Data' => $Data
        ];
        return $this;
    }
}

我们创建用户跟踪存储trait

namespace App\Traits;

use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Route;
use App\Models\UserTracking as ModelUserTracking;

trait UserTracking{

    public function Track($Transaction = true, $Params = []){
        DB::beginTransaction();
        try {
            $UserTracking = new ModelUserTracking;
            $UserTracking->transaction = $Transaction;
            $UserTracking->event = Route::currentRouteName();
            $UserTracking->class = Route::currentRouteAction();
            $UserTracking->request_params = json_encode(request()->all());
            $UserTracking->request_method = Route::current()->methods()[0];
            $UserTracking->request_ip = request()->ip();
            $UserTracking->request_userAgent = request()->userAgent();
            if(!empty($Params)): $UserTracking->params = json_encode($Params); endif;
            $UserTracking->User()->associate(Auth::user());
            $UserTracking->save();

            DB::commit();
        } catch (\Exception $e) {
            DB::rollback();

            Log::error("Insert User Tracking Data Error", [
                'UserTracking' => $UserTracking,
                'Exception' => $e->getMessage()
            ]);
        }
    }

}

现在我们开始构建自定义中间件

自定义中间件:

namespace App\Http\Middleware;

use Closure;
use App\Traits\UserTracking as TraitUserTracking;
use Illuminate\Http\Request;

class UserTracking
{
    use TraitUserTracking;
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure(\Illuminate\Http\Request): (\App\Library\Response\HttpResponse|\App\Library\Response\RedirectResponse)  $next
     * @return \App\Library\Response\HttpResponse|\App\Library\Response\RedirectResponse
     */
    public function handle(Request $request, Closure $next)
    {
        $response = $next($request);

        if(property_exists($response, 'bag'))
            $this->Track($response->bag->Status, $response->bag->Data);

        return $response;
    }
}

本指南的要点是,您应该创建响应的自定义类,并从(Illuminate\Http\Response,Illuminate\Http\RedirectResponse)类扩展它.有了这个技巧,你可以发送和处理任何你喜欢的值.好运

Php相关问答推荐

从AJAX响应中获取一个未定义的html

基于服务器的不同地平线配置

对表示大小的值后缀进行自定义排序(XXS、XS、S、M、L、XL、XXL)

根据WooCommerce的定制订单状态增加产品库存

woocommerce_available_ payment_gateways 过滤器挂钩多次触发

WooCommerce:如果订单总数为零,则隐藏本地取货运输选项

Laravel Eloquent(where 子句)

如何设置Mailersend PHP API 模板变量?

在WooCommerce中显示 checkout 的高级自定义字段(Advanced Custom Fields)并保存其值

WooCommerce - 调用功能ID不正确.不应直接访问订单属性

为 WordPress 页面创建新功能

PHP 中是否有 is_closure() 函数?

列表不在 GROUP BY 子句中并且包含 X2CRM 中的非聚合列

Laravel 从嵌套数组的第二级获取最后一项

如何在运行 update_post_meta 后更新 wp_wc_product_attributes_lookup 表?

如何将文件直接上传到 Cloudinary 而不先保存在 public 文件夹中

如何在不复制的情况下在php中重新索引数组

我的 PHP/Mysql JSON 输出格式与 Flutter 应用所需的示例 JSON 页面格式不同

我想使用 while 在回声中显示回声

如何在 PHP 中创建自定义舍入?