Skip to content

Instantly share code, notes, and snippets.

@zillingen
Last active November 22, 2017 18:38
Show Gist options
  • Save zillingen/3b0ebccd2c0c7621edcfe3c3992016ae to your computer and use it in GitHub Desktop.
Save zillingen/3b0ebccd2c0c7621edcfe3c3992016ae to your computer and use it in GitHub Desktop.
Silex PHP framework gists

Doctrine DBAL base config

<?php
// app/config/db.php

// db config
$app['db.options'] = [
  'driver'   => 'pdo_mysql',
  'host'     => 'localhost',
  'dbname'   => 'silex_app',
  'user'     => 'root',
  'password' => '',
  'charset'  => 'utf8mb4',
  'defaultTableOptions' => ['charset'=> 'utf8mb4', 'collate' => 'utf8mb4_unicode_ci'],
];

Add Doctrine DBAL migrations

1. Install Doctrine Migrations

composer require doctrine/migrations

2. Create migrations folder

Create migrations folder in app folder

mkdir app/migrations

3. Add migrations console commands

Add to your app/console.php file

<?php

use Symfony\Component\Console\Helper\HelperSet;
use Symfony\Component\Console\Helper\QuestionHelper;
use Doctrine\DBAL\Tools\Console\Helper\ConnectionHelper;
use Doctrine\DBAL\Migrations\Configuration\Configuration;

// set db helper
$helperSet = new HelperSet([
    'db' => new ConnectionHelper($app['db']),
    'dialog' => new QuestionHelper()
]);
$console->setHelperSet($helperSet);

// configure doctrine migrations
$configuration = new Configuration($app['db']);
$configuration->setMigrationsTableName('doctrine_migration_versions'); // migrations table name
$configuration->setMigrationsDirectory(__DIR__.'/migrations'); // migrations location folder
$configuration->setMigrationsNamespace('App\DoctrineMigrations'); // genegated migrations namespace

// register migrations commands
$doctrineCommands = [
    new \Doctrine\DBAL\Migrations\Tools\Console\Command\DiffCommand(),
    new \Doctrine\DBAL\Migrations\Tools\Console\Command\ExecuteCommand(),
    new \Doctrine\DBAL\Migrations\Tools\Console\Command\GenerateCommand(),
    new \Doctrine\DBAL\Migrations\Tools\Console\Command\MigrateCommand(),
    new \Doctrine\DBAL\Migrations\Tools\Console\Command\StatusCommand(),
    new \Doctrine\DBAL\Migrations\Tools\Console\Command\VersionCommand()
];
// set configuration for migrations commands
foreach ($doctrineCommands as $command) {
    $command->setMigrationConfiguration($configuration);
}
// add migrations commands
$console->addCommands($doctrineCommands);

4. Generate migration

Run command php bin/console migrations:generate from your Silex project root folder. Then check app/migrations folder, it will contain new created migration class.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment