下面的代码会被认为是“好”的做法吗?
它是包的 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;
}