• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

请问在 构造函数里面,我怎么才能使用 $this->doctrine()->getManager() 这个方法

php 搞代码 3年前 (2022-01-25) 17次浏览 已收录 0个评论
文章目录[隐藏]

我现在的结构是有一个CommonController 然后在里面写了查询菜单的方法,子类继承的时候,还必须得去调用这个方法才行。
能不能在构造函数里面使用 $this->doctrine()->getManager() 这个函数。 我在构造函数里写就报错,找不到has()。
请问该如何做才可以,谢谢~

Parent.php

<code>class AParent{    private $menu;    public function __construct(){            $this->menu = $this->doctrine()->getManager()                        ->getRepository(Menu')->findAll();    }}</code>

Child.php

<code>class Child extends AParent{    public function __construct(){        parent::__construct();        var_dump(parent::$menu);    }}</code>

%本文来源gaodai#ma#com搞*代#码9网#搞gaodaima代码

回复内容:

我现在的结构是有一个CommonController 然后在里面写了查询菜单的方法,子类继承的时候,还必须得去调用这个方法才行。
能不能在构造函数里面使用 $this->doctrine()->getManager() 这个函数。 我在构造函数里写就报错,找不到has()。
请问该如何做才可以,谢谢~

Parent.php

<code>class AParent{    private $menu;    public function __construct(){            $this->menu = $this->doctrine()->getManager()                        ->getRepository(Menu')->findAll();    }}</code>

Child.php

<code>class Child extends AParent{    public function __construct(){        parent::__construct();        var_dump(parent::$menu);    }}</code>

这样是不行的 你要使用 Dependency Injection:

你的

<code>class AParent{    private $menu;    public function __construct(){            $this->menu = $this->doctrine()->getManager()                        ->getRepository('Menu')->findAll();    }}</code>

可以改为:

<code>class AParent{    private $menu;    private $container;    public function __construct( $container){        $this->container = $container    }    public function makeMenu()    {        $this->menu = $this->container->get('doctrine')->getManager()                        ->getRepository('Menu')->findAll();    }    public function getMenu()    {        return $this->menu;    }    public function setMenu( $menu)    {        $this->menu = $menu;        return $this;    }}</code>

在 controller中使用 :

<code>public function indexAction(){    $menuBuilder = new \XXX\XXX\AParent( $this->container );    $menuBuilder->makeMenu();    $menu = $menuBuilder->getMenu();}</code>

你还可以设置成servive:

services.yml:

<code>services:    menu.builder:        class: XXX\XXX\AParent        arguments: [@service_container]</code>

然后在controller中使用 :

<code>public function indexAction(){    $menuBuilder = $this->get('menu.builder');    $menuBuilder->makeMenu();    $menu = $menuBuilder->getMenu();}</code>

搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:请问在 构造函数里面,我怎么才能使用 $this->doctrine()->getManager() 这个方法

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址