zend framework 2 with doctrine, How to reopen the Entitymanager after it was closed by a Exception

633 Views Asked by At

Within an entity's repository, I want to fetch the entity with a given id or create a new one, if the given id is not used so far. My solution is, to create a new entity with the id. If it is possible I return it, if not I want to load the excisting one. Very bad, that it is not possible, cause the entitymanager is closed.

class TestRepository extends Repository {

    // create a new entity or load the existing one
    public function getEntity($pkey) {
        $entity = new Entity($pkey); // create a new entity and set its id to $pkey
        $this->getEntityManager()->persist($language);
        try {
            $this->getEntityManager()->flush(); // success if $pkey isn't used
        } catch (DBALException $e) {
            // this DBALException is catched correct
            // fail - load the existing one
            $entity = $this->find(array($pkey)); // another exception is thrown
            // The EntityManager is closed.
        }
        return $entity;
    }

}

How can I reopen the EntityManger?

1

There are 1 best solutions below

0
On

Why do you try to persist an entity with a defined primary key from which you do not know if it yet exists?

It would be suitable to make a simple find() first and if it returns no result, you create your entity and persists it.

Hope this helps.