Saturday, December 01, 2012

PHP 5.3+ Doctrine2 Schema update script

I have been working more than 3 years with doctrine, and now started to play with Doctrine 2 for few of my new projects, Its almost a year with Doctrine 2. Here is what it helps the team in development.

The command line tool to update tables and dump SQLs for upgrades.


The app uses ZendFramework and Doctrine, here is the small snippet that helps me to run the doctrine commands

$env = getenv('APPLICATION_ENV') ? getenv('APPLICATION_ENV') : 'development';
define('APPLICATION_ENV', $env);
 
define('APPLICATION_PATH', realpath(dirname(__FILE__) . '/../application'));

set_include_path(implode(PATH_SEPARATOR, array(
    realpath(APPLICATION_PATH . '/../library'),
    realpath(APPLICATION_PATH . '/models/entity'),
    realpath(APPLICATION_PATH . '/util'),
    realpath(APPLICATION_PATH . '/models'),  
    get_include_path(),
)));

// Doctrine and Symfony Classes
require_once 'Doctrine/Common/ClassLoader.php';
require_once 'BaseEntity.php';

$classLoader = new \Doctrine\Common\ClassLoader('Doctrine');
$classLoader->register();
$classLoader = new \Doctrine\Common\ClassLoader('Symfony', 'Doctrine');
$classLoader->register();
$classLoader = new \Doctrine\Common\ClassLoader('Entities', APPLICATION_PATH . '/models');
$classLoader->setNamespaceSeparator('_');
$classLoader->register();

// Zend Components
require_once 'Zend/Application.php';
 
// Create application
$application = new Zend_Application(
    APPLICATION_ENV,
    APPLICATION_PATH . '/configs/application.ini'
);

// bootstrap doctrine
$application->getBootstrap()->bootstrap('doctrine');
$em = $application->getBootstrap()->getResource('doctrine');

// generate the Doctrine HelperSet
$helperSet = new \Symfony\Component\Console\Helper\HelperSet(array(
    'db' => new \Doctrine\DBAL\Tools\Console\Helper\ConnectionHelper($em->getConnection()),
    'em' => new \Doctrine\ORM\Tools\Console\Helper\EntityManagerHelper($em)
));

\Doctrine\ORM\Tools\Console\ConsoleRunner::run($helperSet);
The above PHP snippet was saved as doctrine.php And the following commands can be used against the database migrations

> php doctrine.php orm:schema-tool:create
> php doctrine.php orm:schema-tool:update --force
> php doctrine.php orm:schema-tool:update --dump-sql
Trying the following command gives list of other options to perform
>php doctrine.php

No comments:

Post a Comment