doulachan8217 2015-03-27 07:26
浏览 96
已采纳

在Controller构造函数Symfony上加载容器服务

Is there a way to load container service at Controller constructor, like

class PostController extends Controller
{

    protected $breadcrumb;

    public function __construct()
    {
        //initializing breadcrumb
        $breadcrumbs = $this->get("white_october_breadcrumbs");
        $breadcrumbs->addRouteItem("Dashboard", "adminPage");
        $breadcrumbs->addRouteItem("Post", "postPage");
        $this->breadcrumb = $breadcrumbs;
    }
//..
}
  • 写回答

4条回答 默认 最新

  • douluan5738 2015-03-27 07:42
    关注

    Yes, this is possible via Controller as a Service. However, injecting the Container is considered a bad example. If you want to get the service white_october_breadcrumbs, you can just inject this in your controller service definition; If you use yaml:

    service:
        class: app.controller.my_controller
        arguments:
            - "@white_october_breadcrumbs"
    
    public function __construct(Breadcrumbs $breadcrumbs)
    {
        $this->breadcrumbs = $breadcrumbs;
    }
    

    This is a far nicer solution because you don't want your application to depend on the container whenever possible.

    Another solution, considering you want this on multiple pages, would be to use event listeners or even custom annotations on actions to add breadcrumbs dynamically. This is not recommended for beginners though.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 这个复选框什么作用?
  • ¥15 单通道放大电路的工作原理
  • ¥30 YOLO检测微调结果p为1
  • ¥20 求快手直播间榜单匿名采集ID用户名简单能学会的
  • ¥15 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合