I have a controller in my API that contains methods that fetches various data from different tables like account statuses, account types, etc and returns it to the API consumer.
use AppModelsAccountStatus;
use AppModelsAccountType;
use AppModelsAlertLevel;
class ClientController extends Controller
{
public function getAccountStatuses() {
try {
$accountStatuses = AccountStatus::all();
return response()->json([
'error' => false,
'message' => 'OK',
'account_statuses' => $accountStatuses
]);
} catch (Exception $e) {
return response()->json([
'error' => true,
'message' => $e->getMessage() . ' ' . $e->getFile() . ' ' . $e->getLine()
], 500);
}
}
public function getAccountTypes() {
try {
$accountTypes = AccountType::all();
return response()->json([
'error' => false,
'message' => 'OK',
'account_types' => $accountTypes
]);
} catch (Exception $e) {
return response()->json([
'error' => true,
'message' => $e->getMessage() . ' ' . $e->getFile() . ' ' . $e->getLine()
], 500);
}
}
public function getAlertLevels() {
try {
$alertLevels = AlertLevel::all();
return response()->json([
'error' => false,
'message' => 'OK',
'alert_levels' => $alertLevels
]);
} catch (Exception $e) {
return response()->json([
'error' => true,
'message' => $e->getMessage() . ' ' . $e->getFile() . ' ' . $e->getLine()
], 500);
}
}
}
How do i prevent myself from repeating these almost identical code?
3
Answers
If you want to do some clean code, you should create a Class which will contain a function to handle your duplicate code:
This will respect Single Responsability Principle, and in your Controller, just inject it and use it:
You should declare an Interface (
ResponseBuilderInterface
) to inject it, this way your Controller won’t be responsible of injection.Well, there can be many ways to stop repeating the identical codes. It depends on developer’s skills, knowledge and experience. In my case I create A trait file to handel responses.
In Your Clientcontroller.php you can use ResponseHandler.php
Other ways:
You should also try Eloquent: API Resources this can help you to expressively and easily transform your models and model collections into JSON.