Laravel 9 - RateLimiter 无法访问作业中受保护的 属性

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,
}

BUT 如果我将 SendCSToET.php 文件中的 $entry 变量从 protected 更改为 public,代码将按预期运行.我错过了什么?

这是一个简单的 PHP 行为,来自您 RateLimiter 的回调不属于 SendCSToET class 或任何子 class,因此它可以仅访问 public properties/methods。因此,您必须在 public 属性 或 protected + public getter 之间进行选择(更简洁的方式)。

示例 getter SendCSToEt.php 中的函数:

protected $entry;

public function getEntry() {
  return $this->entry;
}