Zend Register EntityManager

Inject ORM entityManager in Controller


1. Installing Doctrine ORM and Migrations

Doctrine installation setup link


2. Create a Factory for MainController (module\Application\src\Controller\Factory\MainControllerFactory.php)

namespace Application\Controller\Factory;
use Psr\Container\ContainerInterface;
use Laminas\ServiceManager\Factory\FactoryInterface;
use Application\Controller\MainController;


class MainControllerFactory implements FactoryInterface
{
    public function __invoke(ContainerInterface $container, $requestedName, array $options = null)
    {
        $entityManager = $container->get('doctrine.entitymanager.orm_default');
        return new MainController($entityManager);
    }
}


3. Register the Factory in module.config.php (module\Application\config\module.config.php)

'controllers' => [
    'factories' => [
        Controller\MainController::class => Controller\Factory\MainControllerFactory::class,
    ],
],


4. Create Controller with Constructor (module\Application\src\Controller\MainController.php)

namespace Application\Controller;

use Laminas\Mvc\Controller\AbstractActionController;
use Application\Entity\User;
use Doctrine\ORM\EntityManager;

class MainController extends AbstractActionController
{
  private $entityManager;

  // Constructor gets EntityManager from factory
  public function __construct(EntityManager $entityManager)
  {
    $this->entityManager = $entityManager;
  }

  public function indexAction()
  {
    $users = $this->entityManager->getRepository(User::class)->findAll();  //get all users data
    return ['users' => $users];
  }
}

Basic Operations with $entityManager

Operation

Method

Example

Persist (Create)

persist($entity)

$entityManager->persist($user);

Save (Flush)

flush()

$entityManager->flush();

Find (By ID)

find(Entity::class, $id)

$entityManager->find(User::class, 1);

Find (By Criteria)

getRepository()->findOneBy([...])

$entityManager->getRepository(User::class)->findOneBy(['email' => 'test@example.com']);

Remove (Delete)

remove($entity) + flush()

$entityManager->remove($user); $entityManager->flush();

Custom Query

createQuery('DQL')

$entityManager->createQuery('SELECT u FROM User u')->getResult();


Whereisstuff is simple learing platform for beginer to advance level to improve there skills in technologies.we will provide all material free of cost.you can write a code in runkit workspace and we provide some extrac features also, you agree to have read and accepted our terms of use, cookie and privacy policy.
© Copyright 2024 www.whereisstuff.com. All rights reserved. Developed by whereisstuff Tech.