Skip to content

A trait to get the object manager and repository for a given class if you're using Doctrine ORM

License

Notifications You must be signed in to change notification settings

Setono/doctrine-orm-trait

Repository files navigation

Doctrine ORM Trait

Latest Version Software License Build Status Code Coverage Mutation testing

If you are like and me and usually don't inject entity managers directly, but inject the manager registry instead then this little library will come in handy.

Installation

composer require setono/doctrine-orm-trait

Usage

<?php
use Doctrine\Persistence\ManagerRegistry;
use Setono\Doctrine\ORMTrait;

final class YourClass
{
    /**
     * Include this trait to use the getManager() and getRepository() methods below
     */
    use ORMTrait;
    
    public function __construct(ManagerRegistry $managerRegistry)
    {
        $this->managerRegistry = $managerRegistry;
    }
    
    public function someMethod(): void
    {
        /**
         * $entity<T> is an entity managed by Doctrine or a class-string representing an entity managed by Doctrine
         */
        $entity = ;
        
        /** @var \Doctrine\ORM\EntityRepository<T> $repository */
        $repository = $this->getRepository($entity);
        
        /** @var \Doctrine\ORM\EntityManagerInterface $manager */
        $manager = $this->getManager($entity);
        
        // or do the following to get the default entity manager
        /** @var \Doctrine\ORM\EntityManagerInterface $manager */
        $manager = $this->getManager();
        
        $manager->persist($entity);
        $manager->flush();
    }
}

About

A trait to get the object manager and repository for a given class if you're using Doctrine ORM

Topics

Resources

License

Stars

Watchers

Forks

Languages