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.

  • 写回答

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条)

报告相同问题?

悬赏问题

  • ¥15 visionmaster启动失败,提示为“机器不满足授权而被禁用”
  • ¥50 用logisim设计16位单时钟周期cpu
  • ¥15 IDEA中圈复杂度如何具体设置
  • ¥50 labview采集不了数据
  • ¥15 请上面代码做什么处理或什么混淆
  • ¥15 英雄联盟自定义房间置顶
  • ¥15 W5500网线插上无反应
  • ¥15 如何用字典的Key,显示在WPF的xaml中
  • ¥15 weautomate读取Excel表格信息然后填写到网页一直报错,如何解决?
  • ¥15 C#如何在Webview2中获取网页验证码