dongpiansui8755 2018-06-01 19:28
浏览 108
已采纳

Symfony基本控制器与前后过滤器

I'm relatively new to Symfony (version 4) and have put together a REST API using the framework.

I have several controllers corresponding to endpoints many of which use common services. One service is common to every controller.

Currently I am injecting these services manually into each controller.

namespace App\Controller;

use Symfony\Component\HttpFoundation\Response;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use App\Services\Utilities;
use App\Services\Database;
use App\Services\Session;
use App\Services\Rest;

class Fetch extends Controller {

    protected $API;
    protected $DB;
    protected $u;

    public function init() {

        $this->API = new Rest();
        $this->DB = new Database();
        $this->u = new Utilities();

        $this->API->init();
        $this->DB->init($this->DB->default_credentials); 

        // .... 

Its kinda repetitive and not very efficient since each class needs to be instantiated every time an endpoint is requested.

There is a need for a global base controller.

Having browsed the Symfony docs & stackoverflow posts, it looks like I can create a base controller and have all my other controllers extend it like so:

class Fetch extends BaseController {
//.....

And all the methods in BaseController will be available in Fetch. Moreover, I can run hooks in BaseController that will run globally (as long as all my controllers extend BaseController.

I have also come upon this symfony docs article describing implementation of "Before and After Filters" that hook into all requests.

Which method (BaseController / Before and After Filters) would be best appropriate for what is effectively some code I want to run globally every time a request is made & why?

  • 写回答

1条回答 默认 最新

  • douchuanghan1344 2018-06-02 08:16
    关注

    Before and After should better then BaseController model, here is why:

    suppose, you write 10 Controller class which extends BaseController class and BaseController class initiate 5 services. the possibility very high that every controller class may not require all 5 services. that will overhead for all 10 controller classes.

    So, if you implement Before/After filter, you define which controller is executing and initiate services which require for this controller.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 基于FOC驱动器,如何实现卡丁车下坡无阻力的遛坡的效果
  • ¥15 IAR程序莫名变量多重定义
  • ¥15 (标签-UDP|关键词-client)
  • ¥15 关于库卡officelite无法与虚拟机通讯的问题
  • ¥100 已有python代码,要求做成可执行程序,程序设计内容不多
  • ¥15 目标检测项目无法读取视频
  • ¥15 GEO datasets中基因芯片数据仅仅提供了normalized signal如何进行差异分析
  • ¥100 求采集电商背景音乐的方法
  • ¥15 数学建模竞赛求指导帮助
  • ¥15 STM32控制MAX7219问题求解答