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

报告相同问题?

悬赏问题

  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法