my question is : How to take my business logic out of controller and transfer it to a service ??? I am currently using two separate controllers for Post model in Laravel. One for user-related logic and one for administrator-related logic. pseudo code for AdminPostController :
class AdminPostController
{
public function index(MaybyIndexRequest $request)
{
$something = do lines of calculation
return return PostResource::collection($something);
}
public function storeAdminPost(StorePostRequest $request)
{
$something = do lines of calculation
return return PostStoreResource::collection($something);
}
}
pseudo code for UserPostController :
class UserPostController
{
public function maybyUserindex(AnotherIndexRequest $request)
{
$something = do lines of calculation
return return UserPostResource::collection($something);
}
public function storeUserPost(OtherStorePostRequest $request)
{
$something = do lines of calculation
return return UserPostStoreResource::collection($something);
}
}
I want to transfer the business logic of these two controllers to another class and call them with the help of, for example, a Facade like : class AdminPostController { public function index(MaybyIndexRequest $request) { $something = PostService::($request); return return PostResource::collection($something); }
public function storeUserPost(StorePostRequest $request)
{
$something = PostService::Store($request);
return return PostStoreResource::collection($something);
}
}
But I do not know with what design patterns I should do this. Or what I'm looking for is not a good way to get the code out of the controller !!! The way to solve this problem came to my mind : factory pattern : a class that has two methods called user() and admin().
class PostFactory
{
public function AdminCommands()
{
return new AdminPostCommands(); // a class that contains admin
}
public function UserCommands()
{
return new UserPostCommands(); // a class that contains user related logics
}
}
That the user method returns an instance of UserPostCommands class (including the user's logic) and the AdminCommands class method (contains the's post logic) .... or :
class PostFactory
{
public function Factory(User $user)
{
if ($user->isAdmin){
return new AdminPostCommands(); // a class that contains admin
}else{
return new UserPostCommands(); // a class that contains user related logics
}
}
a class that it takes an instance of the authorized user to decide whether the AdminPostCommands OR UserPostCommands class should be Returned. each of these two classes(AdminPostCommands or UserPostCommands ) has different methods. For example, the user may not be able to delete a post . Of course, user-related methods will only be used in the user controller and vice versa.
Aucun commentaire:
Enregistrer un commentaire