I have done this countless times now and perhaps it's because autowiring and dependency injection is too complex for me and I just need to work around it, but after consistently searching, I'm still having problems understanding the right way to fix this.
I have this class where I'm trying to create a query from - this is all great and fine as long as I extend "Controller" - as soon as I stray from this, I either get:
$em = new EntityManagerInterface();
$query = $this->em->createQuery('SELECT m FROM App:Main m')
->getResult(\Doctrine\ORM\Query::HYDRATE_ARRAY);
print_r($query);
This is obvious, you cannot instansiate an interface
Cannot instatiate interface Doctrine\ORM\EntityManagerInterface
Or:
Use App\Util\Db\Dbhelper;
$db = $this->container->get(DbHelper::class);
$result = $db->allMains();
Too few arguments to function App\Util\Db|DbHelper::__construct(), 0 passed 1 expected
The other classes are expecting the dependency injection of EntityManagerInterface obviously. All help is greatly appreciated, I don't know why I cannot seem to wrap my head around this properly.
DbHelper Class:
namespace App\Util\Db;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use App\Entity\Main;
class DbHelper
{
protected $em;
public function __construct(EntityManagerInterface $em)
{
$this->em = $em;
}
public function getNames()
{
$names = $this->em->getRepository(Main::class)->findAll();
foreach ($names as $name) {
echo $name->getName();
}
}
}