Replace the default entity manager with new one in Symfony

I’ve a default entity manager which works good and manages the whole entities we have.

But now, I would like to add another entity manager based on the same connection settings except the database name that changed (the credentials, tables etc. are the sames, but in another database).

The config of the default connection:

doctrine:
    dbal:
        default_connection: default_conn
        connections:
            default_conn:
                wrapper_class: ProjectDbalConnectionConnectionWrapper
                url: '%env(DEFAULT_DB_URL)%'

The ConnectionWrapper:

class ConnectionWrapper extends Connection
{
    public function __construct(array $params, Driver $driver, ?Configuration $config = null,
                                ?EventManager $eventManager = null)
    {
        $params['dbname'] = DatabaseSingleton::getInstance();

        parent::__construct($params, $driver, $config, $eventManager);
    }

    public function switch(string $dbName): void
    {
        // close current connection if required
        if ($this->isConnected()) {
            $this->close();
        }

        // replace database url with new database name
        $params = $this->getParams();
        $url = substr($params['url'], 0, strlen($params['url']) - strlen($params['dbname'])) . $dbName;

        // replace connection's params
        $params['url'] = $url;
        $params['dbname'] = $dbName; // new_database_name
        DatabaseSingleton::setValue($dbName);

        // initialize again the connection with updated connection's parameters
        $this->__construct($params, $this->_driver, $this->_config, $this->_eventManager);
    }
}

The code in the controller that carries the change of the database name (that’s to say, the connection (and em) should be changed after calling this controller action):

/**
 * @Route("/e2e", methods={"PATCH"})
 */
public function switchDatabase(Request $request): void
{
   // switch connection's database name
   /** @var ConnectionWrapper $conn */
   $conn = $this->getDoctrine()->getConnection();
   $conn->switch('new_database_name', $logger);

   // creating new entity manager
   /** @var EntityManagerInterface $em */
   $em = $this->getDoctrine()->getManager();
   $this->getDoctrine()->resetManager();
   $newEm = EntityManager::create($conn, $em->getConfiguration(), $em->getEventManager());

   $user = new User('chris');
   $newEm->persist($user);
   $newEm->flush();

   // how to replace the current (old) entity manager with the new one?
   // how to retain this new for all other futures requests?
}

The problem is in other controller, when I want to retrieve my users. It’s the old entity manager (with the old database name) that’s used instead of my new manager..

public function test(EntityManagerInterface $em): JsonResponse
    {
        
        $entities = $em->getRepository(User::class)
                       ->findBy(['username' => 'chris']);

        return new JsonResponse($user); // no result.. !
    }

How to replace the default entity_manager with the new created one on all the Symfony application (and not just inside my controller with $newEm variable).

The problem is I cant use my $newEm for queries in my controller. But I don’t succeed to replace the default entity manager of my Symfony application with this new manager.

PS: my singleton class seems to be not worker…

Source: Symfony Questions

Was this helpful?

0 / 0

Leave a Reply 0

Your email address will not be published. Required fields are marked *