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 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 matlab有关常微分方程的问题求解决
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?
  • ¥100 求三轴之间相互配合画圆以及直线的算法
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考