Would the following code be considered a "good" practice?
It's the controller of an RPC endpoint of a package. The idea is to easily override/extend the validation or authorization for a specific project that includes the package.
Could you say that these are guard clauses or methods? Is it a good idea to have a method which only purpose is to check something and throw an exception if something goes wrong?
The code looks clean to me, but I would to get some advice on this :)
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;
}
Aucun commentaire:
Enregistrer un commentaire