首页 > 解决方案 > 从父类方法返回子方法的可能性?

问题描述

由于我对 Laravel 很陌生,我目前正在使用队列,并且在工作中遇到以下问题。因为我正在调用的 API 可以节流,所以我需要为我调用的每个方法都有这个逻辑,所以我创建了一个父(基)类。(不确定这是否是正确的方法,如果这里有错误也请纠正我)

所以我有JobClass扩展的BaseJobClass,它应该处理 API 客户端的创建。

基本工作

class BaseJob implements ShouldQueue
{
    protected function performActionOrThrottle($method, $parameters, Customer $customer, Marketplace $marketplace) {
        $client = $this->createClient($customer, $marketplace);
        if (!method_exists($client, $method)) {
            return $this->fail(new \Exception("Method {$method} does not exist in " . get_class($client)));
        }
        try {
            $result = $client->{$method}($parameters);
        } catch (\Exception $exception)
        {
            echo $exception->getMessage().PHP_EOL;
            return $this->release(static::THROTTLE_LIMIT);
        }
        return $result;
    }
}

工作

class Job extends BaseJob
{

    CONST THROTTLE_LIMIT = 60;
    CONST RETRY_DELAY = 10;

    private $customer;
    private $requestId;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct(Customer $customer, $requestId = null)
    {
        $this->customer = $customer;
        $this->requestId = $requestId;
        echo "Updating Inventory for {$customer->name}\n";
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        $marketplace = Marketplace::findOrFail(5);

        if (!$report = $this->performActionOrThrottle('GetReport', $this->requestId, $this->customer, $marketplace)) {
            echo "Report not available, trying again in " . self::RETRY_DELAY;
            return $this->release(self::RETRY_DELAY);
        }

        ... 
        handle Data
        ...

        return;
    }
}

为了完成这项工作,我需要返回 handle() 方法。如何从父方法返回句柄方法,而无需检查返回值并实现返回它?如果我愿意,那么让那个父级包含我完成几份工作所需的所有逻辑是没有意义的。

标签: phplaravellaravel-queue

解决方案


推荐阅读