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.

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

报告相同问题?

悬赏问题

  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法