I'm creating api in Lumen framework and recently i read about DRY and service layer. To this day i didn't use any of these in my code and all logic was in the controllers. So i would like to start using it, but i have some problems with it.
This is part of my controller (UsersController.php), because whole code is too long.
<?php
namespace App\Http\Controllers;
use App\User;
use Illuminate\Http\Request;
class UsersController extends Controller
{
private $request;
public function __construct(Request $request) {
$this->request = $request;
}
public function destroy($id) {
$user = User::find($id);
if (!$user) {
return response()->json([
'error' => 'User not found'
], 404);
}
if ($user->role === 'admin') {
return response()->json([
'error' => 'You cant edit admin'
], 403);
}
$user->delete();
return response()->json([], 204);
}
}
After looking at this code i tried to change 2 things.
- Get user and return errors can be done in UserService.php (i have this code in other methods too, so thats why i think thats good idea for this method in service). But as you see i want to return response when there are errors and when i doing it, my code as intented tried to using delete method on json response, not on user model. Throwing exception in my opinion is not good, because is not compatible with DRY principle. Any idea how to fix it?
UserService.php
<?php
namespace App\Services;
use App\User;
class UserService
{
public function getUserById($id)
{
$user = User::find($id);
if (!$user) {
return response()->json([
'error' => 'User not found'
], 404);
}
if ($user->role === 'admin') {
return response()->json([
'error' => 'You cant edit admin'
], 403);
}
return $user;
}
}
Modified UsersController.php/destroy
public function destroy($id) {
$user = $this->userService->getUserById($id);
$user->delete(); // not working because sometimes it can return json response
return response()->json([], 204);
}
- I'm using so much json response in controllers, middlewares etc. and i want to unify this by creating new class, but i dont know how to properly use it. I mean returning json response in ResponderService.php probably wont stop execution in other places like controller. Or maybe i should create this as helper?
ResponderService.php
<?php
namespace App\Services;
class ResponderService
{
private function base($data, $status_code)
{
$data['status_code'] = $status_code;
return response()->json($data, $status_code);
}
public function error($message, $status_code)
{
$data['error'] = $message;
$data['status'] = 'error';
$this->base($data, $status_code);
}
}
I read about Repositories too, but i dont think this pattern would be good in my project. If you have other suggestions that could be improved in controller code, I'm open to them.