Laravel N + 1查询检测器通过减少执行的查询数量,帮助您提高应用程序的性能。 此软件包会在您开发应用程序时实时监控您的查询,并在您应添加预先加载(N + 1个查询)时通知您。
如果你想学习如何自己创建可重用的PHP包,请看Marcel的PHP包开发视频课程。
安装
通过composer安装:
composer require beyondcode/laravel-query-detector --dev
这个扩展包会自动安装好。
用法
如果你的项目应用在debug模式下运行,查询监视器将自动激活。所以你什么都不用做。
默认情况下,这个扩展包会显示一条alert()消息,通知你在当前请求中找到的N+1查询。
如果你希望将此信息写入laravel.log文件、作为警告写入浏览器的控制台日志或新增在Laravel Debugbar (barryvdh/laravel-debugbar)的信息列表中,你可以通过发布配置文件并更改输出行为来实现(请参见下面的示例)。
可以使用以下命令发布包的配置文件:
php artisan vendor:publish --provider=BeyondCode\QueryDetector\QueryDetectorServiceProvider
这将在配置目录中添加querydetector.php文件,其中包含以下内容:
<?php
return [
/*
* Enable or disable the query detection.
* If this is set to "null", the app.debug config value will be used.
*/
'enabled' => env('QUERY_DETECTOR_ENABLED', null),
/*
* Threshold level for the N+1 query detection. If a relation query will be
* executed more then this amount, the detector will notify you about it.
*/
'threshold' => 1,
/*
* Here you can whitelist model relations.
*
* Right now, you need to define the model relation both as the class name and the attribute name on the model.
* So if an "Author" model would have a "posts" relation that points to a "Post" class, you need to add both
* the "posts" attribute and the "Post::class", since the relation can get resolved in multiple ways.
*/
'except' => [
//Author::class => [
// Post::class,
// 'posts',
//]
],
/*
* Define the output format that you want to use. Multiple classes are supported.
* Available options are:
*
* Alert:
* Displays an alert on the website
* \BeyondCode\QueryDetector\Outputs\Alert::class
*
* Console:
* Writes the N+1 queries into your browsers console log
* \BeyondCode\QueryDetector\Outputs\Console::class
*
* Clockwork: (make sure you have the itsgoingd/clockwork package installed)
* Writes the N+1 queries warnings to Clockwork log
* \BeyondCode\QueryDetector\Outputs\Clockwork::class
*
* Debugbar: (make sure you have the barryvdh/laravel-debugbar package installed)
* Writes the N+1 queries into a custom messages collector of Debugbar
* \BeyondCode\QueryDetector\Outputs\Debugbar::class
*
* JSON:
* Writes the N+1 queries into the response body of your JSON responses
* \BeyondCode\QueryDetector\Outputs\Json::class
*
* Log:
* Writes the N+1 queries into the Laravel.log file
* \BeyondCode\QueryDetector\Outputs\Log::class
*/
'output' => [
\BeyondCode\QueryDetector\Outputs\Log::class,
\BeyondCode\QueryDetector\Outputs\Alert::class,
]
];
如果使用Lumen,则需要手动复制配置文件,并在bootstrap/app.php文件中注册Lumen Service Provider:
$app->register(\BeyondCode\QueryDetector\LumenQueryDetectorServiceProvider::class);
如果该扩展包检测到未优化的查询时,你需要运行其他逻辑,则可以侦听\BeyondCode\QueryDetector\Events\QueryDetected事件并编写监听器来运行自己的处理程序。(例如,向Sentry/Bugsnag发送警告、发送延时通知等)
测试
composer test
日志变更
有关最近更改的内容的详细信息,请参阅CHANGELOG。
安全
如果你发现任何与安全相关的问题,请发送电子邮件至marcel@beyondco.de,而不是使用问题跟踪器(Issue Tracker)。
翻译自Marcel