I want to use service layer. but have some questions. I'll provide examples and let's discuss it.
let's say that in a controller store function, I've written the bad code such as I have validation there, I also have model there, give this model user's input's attributes and store it. basically I have everything in a controller which leads to fat controllers. Now, we could do the two things to solve this problem.
1) move validation logic to validation class(easy), then where we create new model instance and set attributes to it and store it in database(that logic is now in controller, but we take it to a model). so that whenever we need the same thing to use in another place, we can call this model's function. if we hadn't done it, we would repeat this logic over and over again. what about business logic? let's take business logic in a service layer. after that our controller will look like this:
public function store(Request $request)
{
DB::beginTransaction();
try{
$results = $this->transport_service->doLogic($request); //makes logic according to user data.
if($results) {
$storeData = Transport::storeTransportThisWay($results, $request); //then we use model's function..
}
DB::commit();
return response()->json(['success'=>'Transport type has been binded to column and its values successfully'], 200);
}catch(\Exception $e){
DB::rollback();
return response()->json(['error'=>'Something went wrong, please try later.'], 500);
}
}
so basically, I write any kind of queries in a model. and any kind of business logic in a service.
First question is : is this a good approach?
2) what we could do is in a controller, let's call service's method in which we write query and also business logic. This is the way everyone uses. but the question is if I follow this approach, let's say in one of the service's one of the methods, I wrote a query and business logic. all works good. but let's say in another I also need to have the same query, but I don't need that business logic. The thing is I can't use that service's method because it has both business logic and query, and I only need query. So the thing is I also have to put query somewhere else, but not in service's method which gives us another question where to put that query. Am I right? if yes, My question is why do people like this approach and why not the first one I mentioned?
Nice example would be much appreciated.
Aucun commentaire:
Enregistrer un commentaire