phpormdoctrine-ormdoctrinelaminas

Problem connecting entitymanager(doctrine) on laminas framework


please tell me how to get entity manager on laminas framework

Controller:

    public function signupAction()
{
    $user = new Users();
    $user->setUsername('Test');
    $user->setEmail('test@mail.ru');
    $user->setNumber('+79168415532');
    
    // this one i have persist() and flush()
}

Solution

  • To elaborate on @Aleksey Blossom's answer you need to create a factory from which to inject the entity manager.

    use Laminas\ServiceManager\Factory\FactoryInterface;
    use Interop\Container\ContainerInterface;
    use Doctrine\ORM\EntityManager;
    use YourModule\Controller\CategoryController;
    
    class CategoryControllerFactory implements FactoryInterface
    {
    
        public function __invoke(ContainerInterface $container, $requestedName, ?array $options = null)
        {
            $entityManger = $container->get(EntityManager::class);
    
            return new CategoryController($entityManger);
        }
    
    }
    

    and in your controller

    use Laminas\Mvc\Controller\AbstractActionController;
    use Doctrine\ORM\EntityManager;
    
        class CategoryController extends AbstractActionController
        {
        
            private EntityManager $entityManager;
        
            public function __construct(EntityManager $entityManager)
            {
                $this->entityManager = $entityManager;
            }
        
            public function signupAction()
            {
                $user = new Users();
                $user->setUsername('Test');
                $user->setEmail('test@mail.ru');
                $user->setNumber('+79168415532');
        
                $this->entityManager->persist($user);
                $this->entityManager->flush();
            }
        
        }
    

    As a side note I would also consider placing your business logic into models.