0

下面的代码会被认为是“好”的做法吗?

它是包的 RPC 端点的控制器。这个想法是轻松覆盖/扩展包含该包的特定项目的验证或授权。

你能说这些是保护条款或方法吗?拥有一个唯一目的是检查某些东西并在出现问题时抛出异常的方法是个好主意吗?

代码对我来说看起来很干净,但我想得到一些建议:)

public function doSomethingWithCustomer() {
    try {
        $this->validate();
        $this->authorize();
        $customer = $this->resolveCustomer();
        $customer->doSomething();
    } catch (HttpException $e) {
        $this->logger->error($e->getMessage());
        return $this->errorResponse($e->getStatusCode(), $e->getMessage());
    }
}

protected function validate()
{
    // Validate input

    if (!$valid) {
        throw new BadRequestHttpException('Invalid email address');
    }
}

protected function authorize()
{
    // Do some authorization checking

    if ($notAuthorized) {
        throw new AccessDeniedHttpException('Not authorized');
    }
}

protected function resolveCustomer()
{
    $customer = Customer::load(1);

    if (is_null($customer) {
        throw new NotFoundHttpException('Customer not found');
    }

    return $customer;
}
4

1 回答 1

2

不,这是一种不好的做法,原因如下:

  1. 你永远不应该捕获一个保护子句异常(它是快速失败方法的一部分)
  2. 方法不能只包含保护子句
  3. 保护子句不应验证业务逻辑

是我的一篇关于保护条款的文章。我希望它能帮助你更好地理解它们。

于 2018-04-11T03:18:22.190 回答