[英]Laravel 9 - RateLimiter unable to access protected property in Job
我一直在嘗試使用 Laravel 9 對作業進行排隊,並設置速率限制,直到我要命中的 API。 限制是每分鍾最多 10 個請求。
我的AppServiceProvider.php
namespace App\Providers;
use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
public function register() {}
public function boot()
{
RateLimiter::for('sendContentStackToEasyTranslate', function($job) {
return Limit::perMinute(10)->by($job->entry->id);
});
}
}
我在SenCSToET.php
作業中的中間件和構造函數
namespace App\Jobs;
use App\Models\ContentStackEntry;
use Exception;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\ClientException;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\Middleware\RateLimited;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Cache;
use IncrediblePony\Auditlog\Traits\AuditlogTrait;
class SendCSToET implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels, AuditlogTrait;
/**
* @var \App\Models\ContentStackEntry
*/
protected $entry;
/**
* Create a new job instance.
*
* @param \App\Models\ContentStackEntry
* @return void
*/
public function __construct(ContentStackEntry $entry)
{
$this->entry = $entry;
}
/**
* Get the middleware the job should pass through.
*
* @return array
*/
public function middleware() {
return [new RateLimited('sendContentStackToEasyTranslate')];
}
}
https://laravel.com/docs/9.x/queues#rate-limiting是我采用這種方法的來源。
當代碼被擊中時,錯誤會出現在我面前:
{
"message": "Cannot access protected property App\\Jobs\\SendCSToET::$entry",
"exception": "Error",
"file": "/var/www/services/test-translation/releases/6/app/Providers/AppServiceProvider.php",
"line": 30,
}
但是,如果我將SendCSToET.php
文件中的$entry
變量從protected
更改為public
,代碼將按預期運行。 我錯過了什么?
這是一個簡單的 PHP 行為,來自RateLimiter
的回調不屬於SendCSToET
class 或任何子類,因此它只能訪問公共屬性/方法。 所以你必須在public
財產或protected
的+ public
吸氣劑(更清潔的方式)之間做出選擇。
SendCSToEt.php 中的 getter SendCSToEt.php
:
protected $entry;
public function getEntry() {
return $this->entry;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.