My current structure is to have a CommonController and then write the query menu method in it. When the subclass inherits, you must call this method. Can I use the $ this-& amp; gt; doctrine ()-& amp; gt; getManager () function in the constructor. In the constructor... my current structure is to have a CommonController and then write the query menu method in it. When the subclass inherits, you must call this method.
Can I use the $ this-> doctrine ()-> getManager () function in the constructor. An error is reported when I write it in the constructor. The has () cannot be found ().
What can I do? Thank you ~
Parent. php
class AParent{ private $menu; public function __construct(){ $this->menu = $this->doctrine()->getManager() ->getRepository(Menu')->findAll(); }}
Child. php
class Child extends AParent{ public function __construct(){ parent::__construct(); var_dump(parent::$menu); }}
Reply content:
My current structure is to have a CommonController and then write the query menu method in it. When the subclass inherits, you must call this method.
Can I use the $ this-> doctrine ()-> getManager () function in the constructor. An error is reported when I write it in the constructor. The has () cannot be found ().
What can I do? Thank you ~
Parent. php
class AParent{ private $menu; public function __construct(){ $this->menu = $this->doctrine()->getManager() ->getRepository(Menu')->findAll(); }}
Child. php
class Child extends AParent{ public function __construct(){ parent::__construct(); var_dump(parent::$menu); }}
If this is the case, you need to use Dependency Injection:
Your
class AParent{ private $menu; public function __construct(){ $this->menu = $this->doctrine()->getManager() ->getRepository('Menu')->findAll(); }}
You can change it:
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; }}
Use in controller:
public function indexAction(){ $menuBuilder = new \XXX\XXX\AParent( $this->container ); $menuBuilder->makeMenu(); $menu = $menuBuilder->getMenu();}
You can also set it to servive:
Services. yml:
services: menu.builder: class: XXX\XXX\AParent arguments: [@service_container]
Then use the following in the controller:
public function indexAction(){ $menuBuilder = $this->get('menu.builder'); $menuBuilder->makeMenu(); $menu = $menuBuilder->getMenu();}