Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Migrations Bundle Laravel Package

dosfarma/migrations-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the Bundle

    composer require dosfarma/migrations-bundle
    
  2. Enable the Bundle Add to config/bundles.php:

    return [
        DosFarma\MigrationsBundle\DosFarmaMigrationsBundle::class => ['dev' => true, 'test' => true],
    ];
    
  3. Configure Basic Parameters Update config/services.yaml with your migration directory and control table:

    parameters:
        dos_farma.migrations.migrations_directory: '%kernel.project_dir%/migrations/postgresql/'
        dos_farma.migrations.control_table: 'migrations'
    
  4. First Migration Generate a migration file using the provided template:

    php bin/console dosfarma:migrations:generate --name="CreateUsersTable"
    

    This creates a .php file in your migrations directory with a Twig-rendered template.

  5. Run Migrations

    php bin/console dosfarma:migrations:migrate
    

First Use Case: Schema Changes

Use this bundle to manage non-Doctrine DBAL migrations (e.g., PostgreSQL-specific extensions, custom SQL, or non-PHP-based migrations). For example:

  • Adding a PostgreSQL extension:
    // migrations/20240101000000_AddPostgresExtension.php
    public function up()
    {
        $this->execute("CREATE EXTENSION IF NOT EXISTS pg_trgm;");
    }
    
  • Running raw SQL:
    public function up()
    {
        $this->execute("ALTER TABLE users ADD COLUMN IF NOT EXISTS bio TEXT;");
    }
    

Implementation Patterns

Workflow Integration

  1. Migration Generation Use the generate command to scaffold migrations with a predefined template (e.g., DBAL SQL or raw SQL):

    php bin/console dosfarma:migrations:generate --template=dbalSql --name="AddIndexToUsers"
    
    • Templates: Override the default template in config/services.yaml or extend via Twig.
  2. Migration Execution

    • Migrate Up:
      php bin/console dosfarma:migrations:migrate
      
    • Rollback:
      php bin/console dosfarma:migrations:rollback
      
    • Status Check:
      php bin/console dosfarma:migrations:status
      
  3. Multi-Engine Support Configure separate adapters for different databases (e.g., PostgreSQL, MySQL) by defining multiple services in services.yaml:

    services:
        dosfarma.migrations.postgres.adapter:
            class: DosFarma\MigrationsBundle\Infrastructure\Service\Phpmig\Adapter\DbalAdapter
            arguments:
                $connection: '@connection.postgres'
                $tableName: 'postgres_migrations'
    
  4. Dependency Injection Inject the ConfigurationContainer into services to programmatically trigger migrations:

    use DosFarma\MigrationsBundle\Infrastructure\Service\Phpmig\ConfigurationContainer;
    
    public function __construct(private ConfigurationContainer $migrations) {}
    
    public function deploy()
    {
        $this->migrations->getMigrator()->migrate();
    }
    

Integration Tips

  • Doctrine DBAL Connection: Ensure your connection.dbal.myservice (or similar) is properly configured in config/packages/doctrine.yaml.
  • Environment-Specific Migrations: Use Symfony’s %env% to dynamically set migration directories:
    parameters:
        dos_farma.migrations.migrations_directory: '%kernel.project_dir%/migrations/%env(DB_ENGINE)%/'
    
  • Custom Migration Classes: Extend the base migration class to add shared logic:
    namespace App\Migrations;
    
    use DosFarma\MigrationsBundle\Infrastructure\Service\Phpmig\Migration;
    
    class BaseMigration extends Migration
    {
        protected function log(string $message) {
            // Custom logging (e.g., to Monolog)
        }
    }
    
    Then reference it in your migration files:
    class AddFeatureFlag extends \App\Migrations\BaseMigration { ... }
    

Gotchas and Tips

Pitfalls

  1. Control Table Conflicts

    • The control_table must exist and be writable. If using a schema (e.g., serviceschema.migrations), ensure the schema exists:
      php bin/console doctrine:schema:create --schema=serviceschema
      
    • Fix: Create the table manually if migrations fail:
      CREATE TABLE serviceschema.migrations (
          version VARCHAR(191) NOT NULL PRIMARY KEY,
          executed_at TIMESTAMP NOT NULL,
          executed_by VARCHAR(191) NOT NULL
      );
      
  2. Template Rendering Issues

    • If migrations fail with Twig errors, verify the template path in dos_farma.migrations.migration_template exists and is accessible.
    • Fix: Use the bundled template as a fallback:
      dos_farma.migrations.migration_template: '%kernel.project_dir%/vendor/dosfarma/migrations-bundle/src/Resources/templates/dbalSql.php.twig'
      
  3. Connection Misconfiguration

    • The adapter requires a valid Doctrine DBAL connection. If migrations hang or fail silently:
      • Check connection.dbal.myservice is defined in services.yaml.
      • Debug: Temporarily add public: true to the adapter service to inspect it:
        DosFarma\MigrationsBundle\Infrastructure\Service\Phpmig\Adapter\Adapter: { ... public: true }
        
        Then dump it in a command:
        $adapter = $container->get('dosfarma.migrations.postgres.adapter');
        var_dump($adapter->getConnection()->getDatabasePlatform());
        
  4. Migration Ordering

    • Files are executed alphabetically by default. Use numeric prefixes (e.g., 20240101000000_) to enforce order.
    • Tip: Add a README.md in your migrations directory to document dependencies between migrations.

Debugging

  1. Verbose Output Enable debug mode for detailed logs:

    php bin/console dosfarma:migrations:migrate --verbose
    
  2. Dry Runs Test migrations without executing them:

    php bin/console dosfarma:migrations:status --dry-run
    
  3. Custom Logging Override the log() method in your migration class to integrate with Monolog or other loggers:

    protected function log(string $message) {
        $this->container->get('logger')->info($message, ['migration' => static::class]);
    }
    

Extension Points

  1. Custom Adapters Extend DbalAdapter to support non-DBAL engines (e.g., MongoDB, Elasticsearch):

    namespace App\Migrations\Adapter;
    
    use DosFarma\MigrationsBundle\Infrastructure\Service\Phpmig\Adapter\AdapterInterface;
    
    class ElasticsearchAdapter implements AdapterInterface
    {
        public function execute(string $sql): void
        {
            // Custom logic for Elasticsearch "migrations"
        }
    }
    

    Register it in services.yaml:

    services:
        dosfarma.migrations.elasticsearch.adapter:
            class: App\Migrations\Adapter\ElasticsearchAdapter
    
  2. Pre/Post Migration Hooks Use Symfony events to run logic before/after migrations:

    # config/services.yaml
    services:
        App\EventSubscriber\MigrationSubscriber:
            tags:
                - { name: kernel.event_subscriber }
    
    namespace App\EventSubscriber;
    
    use DosFarma\MigrationsBundle\Event\MigrationEvents;
    use Symfony\Component\EventDispatcher\EventSubscriberInterface;
    
    class MigrationSubscriber implements EventSubscriberInterface
    {
        public static function getSubscribedEvents(): array
        {
            return [
                MigrationEvents::MIGRATION_PRE_UP => 'onPreUp',
                MigrationEvents::MIGRATION_POST_UP => 'onPostUp',
            ];
        }
    
        public function onPreUp(): void { /* ... */ }
        public function onPostUp(): void { /* ... */ }
    }
    
  3. Migration Validation Add validation to migration files using PHPStan or custom scripts. Example PHPStan rule:

    // phpstan.neon
    parameters:
        level: 8
        paths:
            - migrations
        excludePaths:
            - vendor
    rules:
        DosFarma\MigrationsBundle\:
            - methodCallArgumentType.migrationExecute
    

Performance Tips

  1. Batch Migrations For large migrations, split SQL into smaller batches and use transactions:
    public function up()
    {
        $this->execute("BEGIN;");
        $this->execute("ALTER TABLE large_table ADD COLUMN new_col INT;");
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky