Search code examples
phpdoctrine-ormdoctrine

Performing migration programmatically in Doctrine 2


Given I have a path to Doctrine migration classes. How could I perform the migration programmatically in Doctrine 2?

I assume there should be a clean way to perform the migration over the API as it could have be done with earlier versions of Doctrine as described here: http://docs.doctrine-project.org/projects/doctrine1/en/latest/en/manual/migrations.html


Solution

  • If you work with Doctrine in Symfony framework and found this question looking for ways to run the migrations from outside of the command, keep in mind you can access the already-configured DependencyFactory through autowiring. To do that, expose the service using an alias:

    services:
        Doctrine\Migrations\DependencyFactory:
            alias: 'doctrine.migrations.dependency_factory'
    

    and autowire as usual:

    public function someControllerAction(DependencyFactory $df): Response {
    

    Done.

    In saying so, during normal operation, chances are you should be connecting to the database with a restricted user with no management permissions, following the least-privilege principle. If you do that, running the migrations from your app will fail. If you don't, consider doing it.

    I found the above code to be useful to include the migration information in my health check endpoint response, not necessarily to run the migrations as such.