高阶函数问题

时间:2019-06-02 06:14:28

标签: php laravel

我目前正在阅读Adam Wathan写的《重构集合》一书,并试图通过对正在研究的项目实施高阶函数技术来进行重构。

请求流程:

  • 我正在将有关物业(房屋等)的新记录存储到当前应用程序数据库中
  • 然后,将对2个单独的应用程序进行2次API调用。
  • 记录与API调用之间的所有成功请求和响应
//this is storing new property feature
protected $property;

public function handle(Request $request)
{
    try {
        $databaseConnection->transaction(function() use ($request) { 
            $this->property = $this->run(StorePropertyJob::class, [
                'property' => $this->property,
                'request' => $request
            ]);

            //this will call to an application API
            $this->run(PushAPICallJob::class, [
                'propertyId' => $this->propertyId,
                'name' => $request->input('name'),
                'location' => $request->input('location')
            ]);

            //this will call to separate application API
            $this->run(AnotherPushAPICallJob::class, [
                'propertyId' => $this->propertyId,
                //request will be different
            ]);

            flash('Successfully created '.$request->input('name'));

            return redirect(route('property.index'));
        }); 
    } catch (ApiCallException $e) {
        //logging api error?
        flash('Unable to push to do API call');
    } catch (AnotherApiCallException $e) {
        //logging api error?
        flash('Unable to push to do another API call');
    } catch (Exception $e) { 
        //log the error
        flash('Something went wrong!');
    }

    return back()->withInput();
}

//PushApiCalJob class extending a parent class that has all guzzle set
protected $propertyId;
protected $name;
protected $location;
protected $endPoint = '/property';

public function __construct($propertyId, $name, $location)
{
    $this->requestType = 'POST';
    $this->path = $this->path.$this->endPoint;
    $this->successfulStatusCode = Response::HTTP_CREATED;

    $this->body = [
        'body' => [
            'propertyId' => $propertyId,
            'name' => $name,
            'location' => $location
        ]
    ];

}

public function handle()
{
    $request = $this->client->request($this->requestType, $this->path, $this->body);

    $statusCode = $request->getStatusCode();

    if($statusCode == $this->successfulStatusCode) {
        //this is just basically getting request body content and returning it
    } elseif($statusCode == Request::HTTP_CONFLICT) {
       //this is if it is already existing in the other system
       //need to do logging here - this is a problem
       //this is the return (check point 1 comment below)
    } else {
       //logging for any error - this is also a problem
       //should I throw an exception here?
    }

    throw new ApiCallException();
}

现在我的问题是:

  • 我该怎么做才能使登录到数据库仍然有效?考虑到api调用中的错误将引发异常,因此不包含在事务中。
  • 还有其他更好的方法吗?

0 个答案:

没有答案