Category: Doctrine


After composer requiring doctrine/migrations, you need to edit your cli-config.php. Here’s mine, with the new stuff added in bold.

<?php
use Doctrine\ORM\Tools\Console\ConsoleRunner;
use XYZ\XYZService;
use XYZ\Test\XYZTesting;

// This is just a dependency injection container
$container = XYZTesting::getContainer();

/* Edit these details to suit

$container['db.credentials'] = array(
    'driver' => 'pdo_mysql',
    'dbname' => 'twg',
    'user' => 'dbuser',
    'password' => '123',
];
 */

// this is just my service which returns the entitymanager (requires the DIC above)
$svc = new XYZService($container);
$em = $svc->getEntityManager();
$helperSet = ConsoleRunner::createHelperSet($em);

// Add Doctrine Migration commands
$cli = ConsoleRunner::createApplication($helperSet,[
    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(),
]);

return $cli->run();

Note that I have removed the last line, return ConsoleRunner::createHelperSet($entityManager); and replaced it with return $cli->run(); Now if you type doctrine:

$ doctrine
Doctrine Command Line Interface version 2.5.1

Usage:
command [options] [arguments]

Options:
-h, --help            Display this help message
-q, --quiet           Do not output any message
-V, --version         Display this application version
--ansi            Force ANSI output
--no-ansi         Disable ANSI output
-n, --no-interaction  Do not ask any interactive question
-v|vv|vvv, --verbose  Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug

Available commands:
help                            Displays help for a command
list                            Lists commands
dbal
dbal:import                     Import SQL file(s) directly to Database.
dbal:run-sql                    Executes arbitrary SQL directly from the command line.
migrations
migrations:diff                 Generate a migration by comparing your current database to your mapping information.
migrations:execute              Execute a single migration version up or down manually.
migrations:generate             Generate a blank migration class.
migrations:migrate              Execute a migration to a specified version or the latest available version.
migrations:status               View the status of a set of migrations.
migrations:version              Manually add and delete migration versions from the version table.
orm
orm:clear-cache:metadata        Clear all metadata cache of the various cache drivers.
orm:clear-cache:query           Clear all query cache of the various cache drivers.
orm:clear-cache:result          Clear all result cache of the various cache drivers.
orm:convert-d1-schema           Converts Doctrine 1.X schema into a Doctrine 2.X schema.
orm:convert-mapping             Convert mapping information between supported formats.
orm:convert:d1-schema           Converts Doctrine 1.X schema into a Doctrine 2.X schema.
orm:convert:mapping             Convert mapping information between supported formats.
orm:ensure-production-settings  Verify that Doctrine is properly configured for a production environment.
orm:generate-entities           Generate entity classes and method stubs from your mapping information.
orm:generate-proxies            Generates proxy classes for entity classes.
orm:generate-repositories       Generate repository classes from your mapping information.
orm:generate:entities           Generate entity classes and method stubs from your mapping information.
orm:generate:proxies            Generates proxy classes for entity classes.
orm:generate:repositories       Generate repository classes from your mapping information.
orm:info                        Show basic information about all mapped entities
orm:mapping:describe            Display information about mapped objects
orm:run-dql                     Executes arbitrary DQL directly from the command line.
orm:schema-tool:create          Processes the schema and either create it directly on EntityManager Storage Connection or generate the SQL output.
orm:schema-tool:drop            Drop the complete database schema of EntityManager Storage Connection or generate the corresponding SQL output.
orm:schema-tool:update          Executes (or dumps) the SQL needed to update the database schema to match the current mapping metadata.
orm:validate-schema             Validate the mapping files.

Loads more commands! Now you can start migrating your database properly and safely 🙂 Have fun!

Update
After having run my migrations, it turns out it dumps the migration files in your doc root! After a bit of faffing about, I got the config working, so here is the full cli-config.php:

<?php

use Doctrine\DBAL\Migrations\Configuration\Configuration;
use Doctrine\DBAL\Migrations\Tools\Console\Command\DiffCommand;
use Doctrine\DBAL\Migrations\Tools\Console\Command\ExecuteCommand;
use Doctrine\DBAL\Migrations\Tools\Console\Command\GenerateCommand;
use Doctrine\DBAL\Migrations\Tools\Console\Command\MigrateCommand;
use Doctrine\DBAL\Migrations\Tools\Console\Command\StatusCommand;
use Doctrine\DBAL\Migrations\Tools\Console\Command\VersionCommand;
use Doctrine\ORM\Tools\Console\ConsoleRunner;
use XYZ\XYZService;
use XYZ\Test\XYZTesting;

$container = XYZTesting::getContainer();

/* Edit these details to suit

$container['db.credentials'] = array(
    'driver' => 'pdo_mysql',
    'dbname' => 'XYZ',
    'user' => 'dbuser',
    'password' => '123',
];
 */

// Fetch the entity Manager
$svc = new XYZService($container);
$em = $svc->getEntityManager();

// Create the helperset
$helperSet = ConsoleRunner::createHelperSet($em);

/** Migrations setup */

$configuration = new Configuration($em->getConnection());
$configuration->setMigrationsDirectory('migrations');

$diff = new DiffCommand();
$exec = new ExecuteCommand();
$gen = new GenerateCommand();
$migrate = new MigrateCommand();
$status = new StatusCommand();
$ver = new VersionCommand();

$diff->setMigrationConfiguration($configuration);


$cli = ConsoleRunner::createApplication($helperSet,[
    $diff, $exec, $gen, $migrate, $status, $ver
]);

return $cli->run();

Advertisements

cd-ing into a directory then running ./command, or worse yet, php command.php, sucks!
As an example, I wanted to run the doctrine command from anywhere.
I already have composer installed globally, and no longer have to type php composer.phar, but I haven’t blogged it since it was pretty easy, but anyway here it is:

curl -sS https://getcomposer.org/installer | php
 sudo mv composer.phar /usr/local/bin/composer

Then you can just type composer from anywhere. If you already have composer you should run sudo composer self-update. Anyway on to our php binaries (Doctrine, PHPUnit, Behat, you name it). If it’s a fresh install of composer you should see when you type composer global install:

Composer could not find a composer.json file in /home/username/.composer

Now we know where we can create our composer.json. Go to the sites for the packages you would like and copy paste the require field info; Here is Doctrine’s:

{
    "require":
    {
       "doctrine/dbal": "2.3.4",
       "doctrine/orm": "2.3.5"
    }
}

Now run composer global install and it will install in /home/username/.composer/vendor. The bin folder is inside that. Lastly we need to have our bin path set in our PATH environment variable, so the system knows to check that folder for a binary matching the command’s name. edit ~/.bashrc (it could be .bash_profile or something similar). At the end, paste this in:

export PATH=$PATH:/home/username/.composer/vendor/bin

now exit the shell and open a new terminal up and log back in. you can now type doctrine into the command line and lo and behold, your composer executables are rocking!

Doctrine 2 in a nutshell!

I found this slideshow by the legendary Ocramius (Marco Pivetta). It has all aspects of setting up and using Doctrine 2 (which is fantastic btw, I’ve been using it for a while now) and makes for a nice little introductory tutorial, or, if you are an accomplished PHP developer, a nifty little quick install and go reference!
Anyway, I quite liked it and thought if any of you haven’t tried out the power of Doctrine, go try it now! Go kid go! 😀

http://marco-pivetta.com/doctrine2-orm-tutorial/
(Use the arrow keys to change slides btw (nice little retro touch there 🙂 ))

ZF2 is totally redefining PHP development, I love the direction they are going! Anyway, those who have shown interest will no doubt have played with Akrabats tutorial on the zf2 site. I for one have, and I also went and met the guys themselves at the PHPNW2012 Conference in Manchester at the start of this month! The ZF2 tutorial day was great! Thanks Evan & Rob! Anyway, i’m straying off topic here.

It’s all about the modules! Most sites have a login! A blog! A contact form! Facebook? Twitter? Whatever! Why reinvent the wheel? http://modules.zendframework.com allows you to choose from a growing number of modules, and installing them is a piece of cake (i should stop saying that, this is zend!) using the PHP Composer. So let’s have a look!

Completely starting from scratch, bung this in your Apache’s VirtualHosts config, tweaking the path to wherever your site is:

<VirtualHost *:80>
 ServerName zf2
 DocumentRoot /path/to/my-site/public/
 SetEnv APPLICATION_ENV "development" 
 <Directory /path/to/my-site/public/>
 DirectoryIndex index.php
 AllowOverride All
 Order allow,deny
 Allow from all
 </Directory>
</VirtualHost>

Now you’ve done that, time to install the Zend Framework Skeleton Application, by cloning it from the Git repository. Go into your sites folder, and say:

git clone git:/github.com/zendframework/ZendSkeletonApplication.git my-site
cd my-site
ls

You’ll notice a composer.json in there. Open this up, and you’ll see it depends on PHP and zendframework. In the command prompt:

php composer.phar self-update

This updates composer to the latest version, since it has updated its version since the SkeletonApplication was released. Then:

php composer.phar install

Composer kicks in, and downloads our dependency (zf2), after having made sure you have a sufficient version of PHP (>=5.3).

What’s this? ZF2 recommends installing more modules? Fine, lets do that, but first, lets choose even more modules to add! Change your composer.json to look like this:

{
 "name": "zendframework/skeleton-application",
 "description": "Skeleton Application for ZF2",
 "license": "BSD-3-Clause",
 "keywords": [
 "framework",
 "zf2"
 ],
 "homepage": "http://framework.zend.com/",
 "minimum-stability": "alpha",
 "repositories":[
{
 "type": "composer",
 "url": "http://packages.zendframework.com/"
 }],
 "require": {
 "php": ">=5.3.3",
 "zendframework/zendframework": "2.*",
 "doctrine/doctrine-orm-module": "dev-master",
 "doctrine/doctrine-module": "dev-master",
 "zendframework/zendpdf": "2.*",
 "zendframework/zendservice-recaptcha": "2.*",
 "symfony/yaml": "dev-master",
 "zendframework/zend-developer-tools": "dev-master"
 }
}

I’ve deliberately left two of ZF2s recommendations out of this, as they’re actually pecl extensions, not models, and I ain’t covering that just now, but I added Doctrine functionality. So, to get all this new stuff, we tell Composer to go update itself!

php composer.phar update

And bang, we now have the modules downloaded into the vendor folder. So! How to use them, I hear you cry? Well, the example I’ll show you is probably the best example to start with, and indeed, was the module we were shown at Evan & Rob’s ZF2 Tutorial day at PHPNW2012! ZfcUser.

Goto http://modules.zendframework.com
Scroll down to ZfcUser (formerly EdpUser) (that’s Evan btw) and click, which will take you to the github page.
Scroll down to Requirements. You’ll see you also need ZF2 and ZfcBase to use this module. We have ZF2, but not the ZFCommons base use Classes, so we’ll install both of these. Again, a simple case of adding the lines, then running php composer.phar update. Watch out for unnecessary tabs, brackets, and commas, or the json parser will take a fit!

"zf-commons/zfc-base": "dev-master",
 "zf-commons/zfc-user": "dev-master"

Great! All running smoothly I see! So jump in the ZfcUser module in the vendor folder and go into data, there you’ll get the sql for creating your user table. Run that on your MySQL in your database server, and you’re ready to rock! Now we just need to enable the modules (I’ll only show the relevent ones for the example, so I won’t be using the Doctrine stuff for now) and set up our db connection.

Stick your DB parameters in the config autoload local php file:

return array(
 'db' => array(
 'username' => 'user',
 'password' => 'pass',
 ),
);

and in the global file, we’ll put the meat and bones (the local php file is in .gitignore, which is why we keep the credentials there):

return array(
 'db' => array(
 'driver' => 'Pdo',
 'dsn' => 'mysql:dbname=my-site-db-here;host=localhost',
 'driver_options' => array(
 PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'UTF8\''
 ),
 ),
 'service_manager' => array(
 'factories' => array(
 'Zend\Db\Adapter\Adapter'
 => 'Zend\Db\Adapter\AdapterServiceFactory',
 ),
 ),
);

Now if you open the application config you’ll see an array called modules, where we register the modules our application uses. Change it to this:

'modules' => array(
        'Application',
'ZfcBase', 
'ZfcUser'
    ),

And that’s literally it! try browsing to /user/login! register and login! with Gravatars and everything!

The really great thing about all of these modules is that they are extensible. Is something not happening in a module quite the way you would like it? Write a module extending it!
For instance, my first thought about ZfcUser was ‘what about activating your account by email when you register? Well, guess what? There’s a module for that. Evan told me to go check out CdliTwoStageSignup! (extending ZfcUser)

Working in this manner really is getting to the stage where functionality is literally drag, drop, ‘n’ tell your app! And by studying a module’s code, especially a module extending another module, we can start to see how it all connects up through the service and event managers, and how it’s all tied together! But that’s for you to mess around with! Have fun!

So you have set up doctrine and put it in your servers php library include path. You’ll need this to be in your applications library folder for when you upload it, but rather than copy it in wasting disk space, we’ll symlink it:

ln -s /usr/lib/php/Doctrine ~/Sites/your-site/library/Doctrine

Now lets configure Zend. Open application.ini and bung this stuff in:

autoloaderNamespaces[] = "Doctrine_"
resources.db.adapter = PDO_MYSQL
doctrine.dsn = "mysql://USER:PASS@localhost/DATABASE"

This lets it know about autoloading classes, the type of database adapter we use, and the connection settings. (Be sure to replace USER PASS & DATABASE with your credentials).

Next we initialise Doctrine in the bootstrap:

public function _initDoctrine()
{
    $manager = Doctrine_Manager::getInstance();
    $manager->setAttribute(    Doctrine_Core::ATTR_MODEL_LOADING,        Doctrine_Core::MODEL_LOADING_CONSERVATIVE);
    $config = $this->getOption('doctrine');
    $conn = Doctrine_Manager::connection($config['dsn'],'doctrine');
    return $conn;
}

If all is going well then we should be able to test it out and get a list of databases on the server. In the controller and action of your choosing, try the following out:

// get doctrine manager
 $manager = Doctrine_Manager::getInstance();     
// get connection
$conn = Doctrine_Manager::connection( 'mysql://root@localhost/bzf:[123456]', 'doctrine');
// get databases
$this->view->databases = $conn->import->listDatabases();

At least some things are nice and uncomplicated! Installing Doctrine is simple:

sudo pear channel-discover pear.doctrine-project.org
sudo pear channel-discover pear.symfony.com 
sudo pear install -a pear.doctrine-project.org/DoctrineORM-2.2.2
sudo pear install  pear.doctrine-project.org/DoctrineSymfonyConsole
sudo pear install  pear.doctrine-project.org/DoctrineSymfonyYaml

And if all went to plan you should have the command line interface (CLI)

doctrine -V

Lastly just copy the Doctrine and vendor folders into you php library on the include path.