Giter Site home page Giter Site logo

circlical-collection-hydrator's Introduction

Collection Hydrator

This is a collection hydrator that builds on available hydrators, that prevents cases when Doctrine issues duplicate key updates when Laminas Forms and Collections are involved. This issue can be evidenced here

Usage

Installation is very simple, after installing the package with composer, in your form Factory, you will specify the hydrator strategy for your collection to be "CollectionDiffStrategy".

    <?php
    
    declare(strict_types=1);
    
    namespace HydrationTest\Factory\Form;
    
    use Doctrine\Laminas\Hydrator\DoctrineObject as DoctrineHydrator;
    use Doctrine\ORM\EntityManager;
    use HydrationTest\Form\Hydrator\CollectionDiffStrategy;
    use HydrationTest\Form\IngredientAmountFieldset;
    use HydrationTest\Form\RecipeForm;
    use Laminas\Form\FormElementManager;
    use Laminas\ServiceManager\Factory\FactoryInterface;
    use Psr\Container\ContainerInterface;
    
    class RecipeFormFactory implements FactoryInterface
    {
        public function __invoke(ContainerInterface $container, $requestedName, ?array $options = null)
        {
            $hydrator = new DoctrineHydrator($container->get(EntityManager::class), false);
            $hydrator->addStrategy('ingredient_amounts', new CollectionDiffStrategy(true));
    
            return (new RecipeForm(
                $container->get(FormElementManager::class)->get(IngredientAmountFieldset::class, $options ?? []),
                $options ?? []
            ))
                ->setHydrator($hydrator)
                ->setObject($options['recipe']);
        }
    }

Then, in your fieldset factory, you will apply the CollectionComparatorHydrator to return clean objects of the new type.

    <?php
    
    declare(strict_types=1);
    
    namespace HydrationTest\Factory\Form;
    
    use Doctrine\ORM\EntityManager;
    use HydrationTest\Entity\Ingredient;
    use HydrationTest\Entity\IngredientAmount;
    use HydrationTest\Form\Hydrator\CollectionComparatorHydrator;
    use HydrationTest\Form\IngredientAmountFieldset;
    use Laminas\ServiceManager\Factory\FactoryInterface;
    use Psr\Container\ContainerInterface;
    
    class IngredientAmountFieldsetFactory implements FactoryInterface
    {
        public function __invoke(ContainerInterface $container, $requestedName, ?array $options = null)
        {
            $recipe = $options['recipe'];
    
            /** @var  EntityManager $entityManager */
            $entityManager = $container->get(EntityManager::class);
            $collectionHydrator = new CollectionComparatorHydrator($entityManager, function (array $data, object $object) use ($entityManager, $recipe) {
                $ingredient = $entityManager->getRepository(Ingredient::class)->findOneBy(['id' => $data['ingredient']]);
                return new IngredientAmount($recipe, $ingredient, $data['tablespoons'] ?? 0);
            }, false);
    
    
            return (new IngredientAmountFieldset($entityManager, 'ingredient_amounts'))
                ->setHydrator($collectionHydrator)
                ->setObject(new IngredientAmount($options['recipe'], null, null));
        }
    }

As last step, we must implement the necessary comparators on the objects that are hydrated by the fieldset; see CollectionDiffInterface.

    <?php
    
    declare(strict_types=1);
    
    namespace HydrationTest\Entity;
    
    use Doctrine\ORM\Mapping as ORM;
    use HydrationTest\Model\CollectionDiffInterface;
    
    /**
     * @ORM\Entity
     * @ORM\Table(name="recipes_ingredients");
     */
    class IngredientAmount implements CollectionDiffInterface
    {
        /**
         * @ORM\Id
         * @ORM\ManyToOne(targetEntity="Recipe", inversedBy="ingredient_amounts")
         * @ORM\JoinColumn(name="recipe_id", referencedColumnName="id", onDelete="cascade")
         *
         * @var Recipe
         */
        private $recipe;
    
        /**
         * @ORM\Id
         * @ORM\ManyToOne(targetEntity="Ingredient")
         * @ORM\JoinColumn(name="ingredient_id", referencedColumnName="id", onDelete="cascade")
         *
         * @var ?Ingredient
         */
        private $ingredient;
    
        /**
         * @ORM\Column(type="integer", nullable=false, options={"default":0, "unsigned":true})
         *
         * @var ?int
         */
        private $tablespoons;
    
        public function __construct(Recipe $recipe, ?Ingredient $ingredient, ?int $tablespoons)
        {
            $this->recipe = $recipe;
            $this->ingredient = $ingredient;
            $this->tablespoons = $tablespoons;
        }
    
        public function getIngredient(): Ingredient
        {
            return $this->ingredient;
        }
    
        public function setTablespoons(int $tablespoons): void
        {
            $this->tablespoons = $tablespoons;
        }
    
        public function getTablespoons(): int
        {
            return $this->tablespoons;
        }
    
        public function getDiffIdentifier(): string
        {
            return $this->recipe->getId() . '-' . $this->ingredient->getId();
        }
    
        public function copyValuesFrom(object $object): void
        {
            if (!$object instanceof IngredientAmount) {
                return;
            }
    
            $this->tablespoons = $object->getTablespoons();
        }
    }

After these small changes, your collections will no longer issue update statements that cause duplicate keys.

circlical-collection-hydrator's People

Contributors

saeven avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.