duangaoe9401
2018-08-08 09:08
浏览 31
已采纳

在Symfony中使用服务而不是在控制器中使用服务的最佳做法是什么?

Well i'm learning Symfony (3.3) and i'm little confused about Service Container. In first tutorial the lector show register, login, add post, edit, delete methods in User, Article Controllers. Then in other tutorial, they show same methods but use Service Container (User and Article services) with User and Article interfaces. So .. what is the best practice for implementation in Services instead of Controllers.

图片转代码服务由CSDN问答提供 功能建议

我正在学习Symfony(3.3),我对 Service Container 。 在第一个教程中,lector show注册,登录,添加帖子,编辑,删除用户,文章控制器中的方法。 然后在其他教程中,它们显示相同的方法,但使用服务容器(用户和文章服务)与用户和文章接口。 那么..在服务而不是控制器中实现的最佳实践是什么。

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

3条回答 默认 最新

  • dqwh26750 2018-08-08 09:19
    最佳回答

    Controller must implement the application logic like check if it's a post request or if a form is submit etc... Never use DQL or any SQL Request directly inside a controller !

    EDIT In the example i use a find method inside the controller because it's a Repository method but i parse the result inside slugify (my service method)

    Services contains business logic like formatting phone numbers, parse some data etc... Of course you can inject a repository inside a service and call your methods inside it.

    An example:

    //This is a fictive example
    public function indexAction(Request $request) {
         //Application logic
         if(!$request->get('id')) {
             //redirect somewhere by example
         }
         $article  = $this->getDoctrine()
           ->getRepository(Article::class)
           ->find($request->get('id'));
         //Business Logic
         $slug = $this->get('my.acme.service')->slugify($article->getTitle());
    }
    

    Hope this helps

    评论
    解决 无用
    打赏 举报
查看更多回答(2条)

相关推荐 更多相似问题