Symfony 3.4 supports rewriting of container->get().
I was changing get("doctrine")->getManager(), but there was a place where information was passed in () to getManager as shown below.
In such a case, how should I rewrite it?
Problem Code
protected function execute(InputInterface $input, OutputInterface $output)
{
$em = $this->getContainer()->get("doctrine")->getManager('mkt');
$this->conn = $em->getConnection();
}
Normal changes
Before
protected function execute(InputInterface $input, OutputInterface $output)
{
$em = $this->getContainer()->get("doctrine")->getManager('mkt');
$this->conn = $em->getConnection();
}
After
use Doctrine\ORM\EntityManagerInterface;
class ~
{
protected $em;
public function __construct(EntityManagerInterface $em)
{
$this->em = $em;
parent::__construct();
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$this->conn = $this->em->getConnection();
}
}
My Answer:
In order to rewrite the code to use automatic wiring when the DB information is specified in getManager, you can modify the constructor of your class to accept the EntityManagerInterface as a parameter. Then, you can inject the EntityManager into your class using dependency injection.
Here is how you can rewrite the code:
php
use Doctrine\ORM\EntityManagerInterface;
class YourClass
{
protected $em;
public function __construct(EntityManagerInterface $em)
{
$this->em = $em;
parent::__construct();
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$this->conn = $this->em->getConnection();
}
}
By doing this, you are no longer directly calling getManager('mkt') in your code, but instead injecting the EntityManager into your class. This allows for better decoupling and makes your code more testable and maintainable.
Rate this post
5 of 5 based on 3888 votesComments