Hi,
Whats the correct way to use doctrine in Mezzio? Specifically how to obtain instance of the Doctrine\ORM\EntityManager from the container within a factory to pass as constructor argument of related handler?
I’m currently getting ‘You have requested a non-existent service “Doctrine\ORM\EntityManagerInterface”’ and also unsure how and where to define the database parameters in my module.
I have the following factory:
final class UsersHandlerFactory
{
public function __invoke(ContainerInterface $container): RequestHandlerInterface
{
$entityManager = $container->get(EntityManagerInterface::class);
return new UsersHandler($entityManager);
}
}
and in related handler:
public function __construct(private EntityManagerInterface $entityManager)
{
}
and config:
public function getDependencies(): array
{
return [
'invokables' => [],
'factories' => [
Handler\UsersHandler::class => Handler\UsersHandlerFactory::class,
],
];
}
The correct way retrieving an EntityManager instance from the service container is …
<?php
declare(strict_types=1);
namespace Marcel\Factory;
use Doctrine\ORM\EntityManager;
...
public function __invoke(ContainerInterface $container): RequestHandlerInterface
{
$entityManager = $container->get(EntityManager::class);
return new UsersHandler($entityManager);
}
...
Instead of getting EntityManagerInterface::class just use EntityManager::class. That should fix your issue. The type hints are okay, because the entity manager implements the interface. I personally use Doctrine\Persistence\ObjectManager as type hint, because it 's the most basic interface. Using the EntityManagerInterface is fine, too.
Hi @ezkimo,
Thanks for the reply but unfortunately that did not work either. Still requesting a non existent service.
I’ll need to investigate further to establish where the services get defined and how to inspect whats available in the container.
Hi - thanks for the reply. Yes was using that but had it incorrectly configured. I’ve moved the config into: config/autoload/development.local.php
which hopefully is correct, but then receive another error: Class "Doctrine\Common\Cache\ArrayCache" not found
So need to familiarise myself with the config side of things more
If you are willing to dig into some code, you can have a look at a real-life example.
We configure roave/psr-container-doctrine in config/autoload/doctrine.global.php. It could be a different file name, but it make sense to me to split doctrine stuff from other things. (the actual login/password will be in a non-versioned config/autoload/local.php).
In our case our custom EntityManagerFactory is pretty straighforward and is only needed for our special use of filters. Most likely you can take a shortcut and configure the container directly with \Roave\PsrContainerDoctrine\EntityManagerFactory instead.