当我使用laravel修补程序会话在Observer类中摆弄模型时,有什么方法可以捕捉? [英] Is there a way to catch when I'm using a laravel tinker session to fiddle with the Models in an Observer class?

查看:89
本文介绍了当我使用laravel修补程序会话在Observer类中摆弄模型时,有什么方法可以捕捉?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将Observer设置为侦听Model的事件,以保持我的Controller清除日志消息.我的实现如下:

I have an Observer set up to Listen to a Model's events in order to keep my Controller clean of Logging messages. My implementation is as follows:

首先,一个存储方法执行应做的事情.根据有效参数创建并保存新模型.

First, a store method that does just what it's supposed to do. Create and save a new model from valid parameters.

# app/Http/Controllers/ExampleController.php
namespace App\Http\Controllers;

use App\Http\Requests\StoreExample;
use App\Example;

class ExampleController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');
    }

    /**
     * Create and save an Example from validated form parameters.
     * @param  App\Http\Requests\StoreExample  $request
     */
    public function store(StoreExample $request)
    {
        Example::create($request->validated());

        return back();
    }
}

StoreExample表单请求并不重要.它只是验证并检查授权动作的门.

The StoreExample Form Request isn't important. It just validates and checks a gate to authorize the action.

我设置的Observer记录了此操作.

The Observer I have set up logs this action.

# app/Observers/ExampleObserver.php
namespace App\Observers;

use App\Example;

class ExampleObserver
{
    public function created(Example $example): void
    {
        \Log::info(auth()->id()." (".auth()->user()->full_name.") has created Example with params:\n{$example}");
    }
}

我遇到的问题是,我的日志依赖于要设置的auth()对象的方式.鉴于auth中间件和它必须检查以存储示例的门,来宾用户无法取消此代码.

The problem I have, is the way my logs depend on the auth() object to be set. Given the auth middleware and the gate it has to check in order to store an Example, there is no way a guest user will set off this code.

但是,我确实喜欢在本地和暂存环境中使用tinker来检查网站的行为,但这会引起错误(更准确地说,是PHP notice),因为我可以创建模型而未通过身份验证,则记录器将尝试从非对象auth()->user()中获取属性full_name.

However, I do like to use tinker in my local and staging environments to check the behavior of the site but that can set off an error (Well, PHP notice to be more precise) because I can create Example models without being authenticated and the logger will try to fetch the property full_name from the non-object auth()->user().

所以我的问题如下:当我专门使用Laravel tinker会话来处理Observer类中的模型时,是否有一种方法可以捕获?

So my question is as follows: Is there a way to catch when I'm specifically using the Laravel tinker session to handle my models in the Observer class?

推荐答案

好的,回答我自己的问题: IS 是一种方法.它需要使用Request对象. 由于观察者并不自己处理请求,因此我在构造函数中注入了一个请求. 可以使用request()代替,因此不需要DI.

Okay, replying to my own question: There IS a way. It requires using a Request object. Since observers do not deal with requests on their own, I injected one in the constructor. request() can be used instead, so no DI is needed.

因为请求对象具有可访问的$ server属性,该属性包含我想要的信息.这是我通过返回dd($request->server)获得的相关信息(我不会粘贴整个内容.我的请求的ServerBag具有超过100个属性!)

Because a request object has an accessible $server attribute that has the information I want. This is the relevant information I get by returning a dd($request->server) (I'm not gonna paste the whole thing. My Request's ServerBag has over 100 attributes!)

Symfony\Component\HttpFoundation\ServerBag {#37
  #parameters: array:123 [
    "SERVER_NAME" => "localhost"
    "SERVER_PORT" => 8000
    "HTTP_HOST" => "localhost:8000"
    "HTTP_USER_AGENT" => "Symfony"   // Relevant
    "REMOTE_ADDR" => "127.0.0.1"
    "SCRIPT_NAME" => "artisan"       // Relevant
    "SCRIPT_FILENAME" => "artisan"   // Relevant
    "PHP_SELF" => "artisan"          // Relevant
    "PATH_TRANSLATED" => "artisan"   // Relevant
    "argv" => array:2 [              // Relevant
      0 => "artisan"
      1 => "tinker"
    ]
    "argc" => 2
  ]
}

因此,我可以使用$request->server('attribute')过滤所有这些属性(返回$request->server->attributenull,因此没有访问未定义属性的风险).我也可以执行$request->server->has('attribute')(返回truefalse)

So there's all these attributes I can filter by using $request->server('attribute') (returns $request->server->attribute or null, so no risk of accessing an undefined property). I can also do $request->server->has('attribute') (returns true or false)

# app/Observers/ExampleObserver.php
namespace App\Observers;

use App\Example;

class ExampleObserver
{
    /* Since we can use request(), there's no need to inject a Request into the constructor
    protected $request;

    public function __construct(Request $request)
    {
        $this->request = $request;
    }
    */

    public function created(Example $example): void
    {
        \Log::info($this->getUserInfo()." has created Example with params:\n{$example}");
    }

    private function getUserInfo(): string
    {
        // My logic here. 
    }
}

这篇关于当我使用laravel修补程序会话在Observer类中摆弄模型时,有什么方法可以捕捉?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆