I want to implement a Service pattern to keep my Controller thin. One thing I’m not sure is whether I need to put the validation in the Service or let it stay in the Controller.
For example, I have a UserRegistration controller, so I have kind of this register
method:
class UserRegistrationController
{
public function register($request)
{
$credentials = array_get($request, ['username', 'email', 'password']);
$validator = [
'username' => 'required|min:5',
'email' => 'required|email',
'password' => 'required'
];
if (! $this->validator->validate($credentials, $validator)) {
// return and shows error
}
$this->registrationService->register($credentials);
// return and shows success
}
}
If I put the validation in the Controller, then in my Service class, I assume the credentials are correct, so I just store the user to the db.
class RegistrationService
{
public function register($credentials)
{
$user = new UserModel;
$user->name = $credentials['username'];
$user->email = $credentials['email'];
$user->password = hash($credentials['password']);
$user->save();
// send welcome email
}
}
Which one is the best practice? Make the Service class error proof or just leave it like above?