In my project I am using the ADR architecture, a branch of MVC.
In my actions (Controllers) I handle only data that comes from the request.
When there is a business rule that defines which status code I return, I do this treatment in my service.
Imagine this scenario:
When editing a user, I check if the user's email already exists, if it exists, I return an error informed to your message. This treatment is done in the service, and in these cases I get the error in it.
I would like to hear from you about my approach to, in some cases, the service layer returning the payload.
Action:
class CreateUserAction extends Action
{
private $userService;
/**
* @param UserService $userService
*/
public function __construct(UserService $userService)
{
$this->userService = $userService;
}
public function handle(Request $request) : JsonResponse
{
$data = $request->getData();
$payload = $this->userService->create($data, $user);
return response()->json($payload->body, $payload->statusCode);
}
}
Service:
class UserService extends BaseService
{
private $userRepository;
public function __construct(UserRepository $userRepository)
{
$this->userRepository = $userRepository;
}
public function create(array $data) : object
{
if ($this->userRepository->findByEmail($data['email'])) {
$this->setPayloadError(
__('messages.user.contributor_email_already_exists'),
Response::HTTP_BAD_REQUEST
);
return $this->getPayload();
}
$userCreated = $this->userRepository->create($data);
$this->setPayload($userCreated, Response::HTTP_CREATED);
return $this->getPayload();
}
}
```