The document provides information about new features and integration of Symfony and Doctrine. It discusses updates to the DoctrineBundle and new bundles for MongoDB integration and database migrations. It also covers using the Doctrine database abstraction layer independently and the object relational mapper, including entity management, querying, and schema management.
Performance and testing are just one aspect of code, to really be successful your code needs to be readable, maintainable and generally easier to comprehend and work with. This talk draws from my own experience in applying the techniques of object calisthenics and code readability, within an existing team. It will help you identify trouble areas, learn how to refactor them and train you to write better code in future projects avoiding common pitfalls.
Lithium: The Framework for People Who Hate FrameworksNate Abele
This is the presentation was given at ConFoo on March 11th by Nate Abele and Joël Perras, and is an introduction to the architectural problems with other frameworks that Lithium was designed to address, and how it addresses them. It also introduces programming paradigms like functional and aspect-oriented programming which address issues that OOP doesn't account for.
Finally, the talk provides a quick overview of the innovative and unparalleled features that Lithium provides, including the data layer, which supports both relational and non-relational databases.
Performance and testing are just one aspect of code, to really be successful your code needs to be readable, maintainable and generally easier to comprehend and work with. This talk draws from my own experience in applying the techniques of object calisthenics and code readability, within an existing team. It will help you identify trouble areas, learn how to refactor them and train you to write better code in future projects avoiding common pitfalls.
Lithium: The Framework for People Who Hate FrameworksNate Abele
This is the presentation was given at ConFoo on March 11th by Nate Abele and Joël Perras, and is an introduction to the architectural problems with other frameworks that Lithium was designed to address, and how it addresses them. It also introduces programming paradigms like functional and aspect-oriented programming which address issues that OOP doesn't account for.
Finally, the talk provides a quick overview of the innovative and unparalleled features that Lithium provides, including the data layer, which supports both relational and non-relational databases.
A lot of people using PHPunit for testing their source code. While I was observing my team
I recognized most of them are only using the standard ssertions like 'assertEquals()' or
'assertTrue()' and are complaining about how hard it is to test the code even when the tests are written first. This talk is about all the stuff not used on a daily basis. It shows you some nice features of PHPUnit and how to use them for your benefit.
JavaScript Fundamentals with Angular and LodashBret Little
The purpose of this presentation is also largely to explain some of the fun parts of JavaScript (dynamic function invocation with reflection, dynamic arguments, etc). I don't necessarily encourage putting complex logic throughout your templates with lodash, though there may be times it is appropriate.
Lets talk about lodash and how it can easily be married to Angular. Using a six line filter, I will expose the power of lodash directly within angular templates. This will be an introduction to lodash, angular templates, and we'll talk about scope and reflection within JavaScript.
Building Lithium Apps (Like a Boss) was a workshop presented on the structure and philosophy of the Lithium framework and its applications, and how best to take advantage of them.
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYAMaulik Borsaniya
Classes and Object-oriented Programming:
Classes: Creating a Class, The Self Variable, Constructor, Types of Variables, Namespaces, Types of Methods (Instance Methods, Class Methods, Static Methods), Passing Members of One Class to Another Class, Inner Classes
Inheritance and Polymorphism: Constructors in Inheritance, Overriding Super Class Constructors and Methods, The super() Method, Types of Inheritance, Single Inheritance, Multiple Inheritance, Method Resolution Order (MRO), Polymorphism, Duck Typing Philosophy of Python, Operator Overloading, Method Overloading, Method Overriding
Abstract Classes and Interfaces: Abstract Method and Abstract Class, Interfaces in Python, Abstract Classes vs. Interfaces,
Inheritance and Polymorphism in Python. Inheritance is a mechanism which allows us to create a new class – known as child class – that is based upon an existing class – the parent class, by adding new attributes and methods on top of the existing class.
MongoDB es un motor de base de datos NoSQL que ha ganado mucha popularidad en los últimos tiempos, ya que ofrece muchos beneficios a la hora de desarrollar aplicaciones web.
En esta charla daremos una breve introducción a su instalación, configuración y funcionamiento. Luego repasaremos las distintas alternativas a la hora de usarlo en nuestras aplicaciones desarrolladas con PHP y Symfony2, y explicaremos cómo puede incrementar la velocidad de desarrollo y ayudar con aplicaciones web de alto rendimiento.
A lot of people using PHPunit for testing their source code. While I was observing my team
I recognized most of them are only using the standard ssertions like 'assertEquals()' or
'assertTrue()' and are complaining about how hard it is to test the code even when the tests are written first. This talk is about all the stuff not used on a daily basis. It shows you some nice features of PHPUnit and how to use them for your benefit.
JavaScript Fundamentals with Angular and LodashBret Little
The purpose of this presentation is also largely to explain some of the fun parts of JavaScript (dynamic function invocation with reflection, dynamic arguments, etc). I don't necessarily encourage putting complex logic throughout your templates with lodash, though there may be times it is appropriate.
Lets talk about lodash and how it can easily be married to Angular. Using a six line filter, I will expose the power of lodash directly within angular templates. This will be an introduction to lodash, angular templates, and we'll talk about scope and reflection within JavaScript.
Building Lithium Apps (Like a Boss) was a workshop presented on the structure and philosophy of the Lithium framework and its applications, and how best to take advantage of them.
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYAMaulik Borsaniya
Classes and Object-oriented Programming:
Classes: Creating a Class, The Self Variable, Constructor, Types of Variables, Namespaces, Types of Methods (Instance Methods, Class Methods, Static Methods), Passing Members of One Class to Another Class, Inner Classes
Inheritance and Polymorphism: Constructors in Inheritance, Overriding Super Class Constructors and Methods, The super() Method, Types of Inheritance, Single Inheritance, Multiple Inheritance, Method Resolution Order (MRO), Polymorphism, Duck Typing Philosophy of Python, Operator Overloading, Method Overloading, Method Overriding
Abstract Classes and Interfaces: Abstract Method and Abstract Class, Interfaces in Python, Abstract Classes vs. Interfaces,
Inheritance and Polymorphism in Python. Inheritance is a mechanism which allows us to create a new class – known as child class – that is based upon an existing class – the parent class, by adding new attributes and methods on top of the existing class.
MongoDB es un motor de base de datos NoSQL que ha ganado mucha popularidad en los últimos tiempos, ya que ofrece muchos beneficios a la hora de desarrollar aplicaciones web.
En esta charla daremos una breve introducción a su instalación, configuración y funcionamiento. Luego repasaremos las distintas alternativas a la hora de usarlo en nuestras aplicaciones desarrolladas con PHP y Symfony2, y explicaremos cómo puede incrementar la velocidad de desarrollo y ayudar con aplicaciones web de alto rendimiento.
This is a set of slides purely for presentation along with my talk on "Understanding Doctrine" at True North PHP 2013.
The content of the presentation is available at https://github.com/shiroyuki/trphp13-demo/blob/master/notes/speaker-note.md.
Presentation gave at ConFoo 2012 (2012-03-01)
As soon as you decide to use an ORM tool, one of the biggest factors is Rapid Application Development.
Everything is wonderful during development phase, but when it hits production, performance doesn't work like you expect.
You may think it's ORM's fault, your expected it to write as efficient queries as you manually do, but like guns, ORMs don't kill your database, developers do!
This talk will go deep into Doctrine 2 ORM by exploring performance tips that can save your application from its deepest nightmare.
Effective Doctrine2: Performance Tips for Symfony2 DevelopersMarcin Chwedziak
How to boost performance Doctrine2 with Symfony2. How to configure metadata caching? How to optimize DQL queries for caching. How to properly setup transaction demarcation with EntityManager. How to deal with EntityManager and Listeners with Symfony2 container.
See how to use MongoDB in Symfony2 projects to speed up the development of web applications. We will give an introduction of MongoDB as a NoSQL database server and look at the options on how to work with it from Symfony2 and PHP applications.
Ralph Schindler (of Zend Framework) and Jon Wage (of Doctrine) presented these slides for a webinar hosted by zend.com (webinar available online).
Links are contained within the slides to the demo application that was also used during the webinar.
Drupal Camp Porto - Developing with Drupal: First StepsLuís Carneiro
The goal of this presentation is to give Drupal new comers some insights about key aspects of developing with Drupal.
The idea is to give the audience some guidelines about good practices of Drupal development along with some tips and, by a simple example application, present the most common and important structures/characteristics of the Drupal API.
This talk represents the combined experience from several web development teams who have been using Symfony2 since months already to create high profile production applications. The aim is to give the audience real world advice on how to best leverage Symfony2, the current rough spots and how to work around them. Aside from covering how to implement functionality in Symfony2, this talk will also cover topics such as how to best integrate 3rd party bundles and where to find them as well as how to deploy the code and integrate into the entire server setup.
Easier building complex applications in Joomla! by adding a mapping layer between the domain model and the database. Some of this might be useful to improve Joomla!'s core.
While building custom Joomla!-extensions I often encountered difficulties implementing one-to-many and many-to-many relations.
Joomla! uses lists and items, where a list relates to a database table and an item to a record in that table. Because the underlying relational database is normalised, fields are atomic: contain only one value. In reality (in the domain) a person can have multiple addresses, an order can have multiple orderlines, a posting can have several comments, a product can have several images etc. Often, fields in our entities are not atomic, but can have collections of values. If we stay close to the one-to-one mapping of lists/items and database tables, as Joomla! natively does, it soon becomes messy when modelling more complex relationships. But if we use a mapping between the objects in our domain model and the database, we can easily use non-atomic fields. The same holds for inheritance mapping: a parent class and child classes can be mapped to a relational database in several ways. The Unified Content Model (UCM) is an example of class table inheritance mapping, where the superclass (core_content) has its own table, as do the subclasses. This opposed to the currently used concrete table inheritance, where every content-type maps to one table.
Fortunately this Object Relational Mapping has allready been extensively elaborated. No need to reinvent this wheel. In this presentation I'll show how I used Doctrine ORM for it. And I'll show how this could be used to improve Joomla!'s core.
Multi-Tenancy is a critical component of any Software as a Service (SaaS) application, which enables one application instance to serve multiple organizations, or tenants. This presentation by Scott Crespo covers the basics of multi-tenant architectures, and how to implement multi-tenancy using Python, Django, and the open-source project known as Django Tenant Schemas.
The Bundle system is one of the greatest and most powerful features of Symfony2. Bundles contain all the files related to a single feature of your application: controllers, entities, event listeners, form types, Twig templates, etc. But how much of that actually needs to be inside a bundle?
In this talk we’ll take a bundle, containing all those different types of classes, configuration files and templates, and strip it down to the bare necessities. And I promise that after moving many files out of the bundle, everything still works.
While looking for ways to move things out of the bundle, I will discuss some of the more advanced features of bundle design, like prepending configuration, compiler passes and Doctrine mapping drivers. We will end with a very lean bundle, surrounded by a few highly reusable, maximally decoupled libraries.
Talk about add proxy user in Spark Task execution time given in Spark Summit East 2017 by Jorge López-Malla and Abel Ricon
full video:
https://www.youtube.com/watch?v=VaU1xC0Rixo&feature=youtu.be
Singletons in PHP - Why they are bad and how you can eliminate them from your...go_oh
While Singletons have become a Pattern-Non-Grata over the years, you still find it surprisingly often in PHP applications and frameworks. This talk will explain what the Singleton pattern is, how it works in PHP and why you should avoid it in your application.
A presentation I gave on September 26 at the Melbourne Symfony developers group on using Environment Variables (envvars) in Symfony and managing secrets in your PHP applications.
For more information on these subjects, check out the supporting piece I wrote: https://samjarrett.com.au/swipe-right
Similar to Symfony2 and Doctrine2 Integration (20)
Come to this talk prepared to learn about the Doctrine PHP open source project. The Doctrine project has been around for over a decade and has evolved from database abstraction software that dates back to the PEAR days. The packages provided by the Doctrine project have been downloaded almost 500 million times from packagist. In this talk we will take you through how to get started with Doctrine and how to take advantage of some of the more advanced features.
Doctrine 2: Enterprise Persistence Layer for PHPJonathan Wage
Doctrine 2 is an object relational mapper (ORM) for PHP 5.3+ that sits on top of a powerful database abstraction layer (DBAL). One of its key features is the option to write database queries in a proprietary object oriented SQL dialect called Doctrine Query Language (DQL), inspired by Hibernates HQL. This provides developers with a powerful alternative to SQL that maintains flexibility without requiring unnecessary code duplication.
3. DoctrineMongoDBBundle
• MongoDB Object Document Mapper
– Transparent persistence to MongoDB
– Same architecture as ORM
– Map a class as an entity and document
Doctrine 2 www.doctrine-project.org www.sensiolabs.com
4. DoctrineMigrationsBundle
• Integration with the database migrations
project.
• Easily manage and deploy different versions
of your database.
• Generate migrations when you change your
schema mapping information
Doctrine 2 www.doctrine-project.org www.sensiolabs.com
5. DBAL
• To use just the DBAL you must configure it:
doctrine.dbal:
dbname: Symfony
user: root
password: ~
Doctrine 2 www.doctrine-project.org www.sensiolabs.com
6. DBAL
• If you need to specify multiple connections
you can use the following syntax:
doctrine.dbal:
default_connection: default
connections:
default:
driver: PDOSqlite
dbname: Symfony
user: root
password: null
host: localhost
port: ~
path: %kernel.data_dir%/symfony.sqlite
event_manager_class: DoctrineCommonEventManager
configuration_class: DoctrineDBALConfiguration
wrapper_class: ~
options: []
Doctrine 2 www.doctrine-project.org www.sensiolabs.com
7. DBAL Console Commands
• Create all configured databases
$ php console doctrine:database:create
• Create a specific database
$ php console doctrine:database:create --connection=default
• Drop all configured databases
$ php console doctrine:database:drop
• Drop a specific database
$ php console doctrine:database:drop --connection=default
Doctrine 2 www.doctrine-project.org www.sensiolabs.com
9. DBAL
• Get the default configured database
connection:
class MyController extends DoctrineController
{
public function indexAction()
{
$conn = $this->getDatabaseConnection();
// ...
}
}
Doctrine 2 www.doctrine-project.org www.sensiolabs.com
10. DBAL
• Get a configured database connection service
by its name:
class MyController extends DoctrineController
{
public function indexAction()
{
$conn = $this->getDatabaseConnection('default');
// ...
}
}
Doctrine 2 www.doctrine-project.org www.sensiolabs.com
11. ORM
• The EntityManager
• Central place for persisting and retrieving entities
• Multiple instances allowed
• One EntityManager per database connection
$config = new DoctrineORMConfiguration();
$config->setMetadataCacheImpl(new DoctrineCommonCacheArrayCache);
$driverImpl = $config->newDefaultAnnotationDriver(array(__DIR__."/Entities"));
$config->setMetadataDriverImpl($driverImpl);
$config->setProxyDir(__DIR__ . '/Proxies');
$config->setProxyNamespace('Proxies');
$connectionOptions = array(
'driver' => 'pdo_sqlite',
'path' => 'database.sqlite'
);
$em = DoctrineORMEntityManager::create($connectionOptions, $config);
• Dependency Injection handles the creation and
management of entity manager services
Doctrine 2 www.doctrine-project.org www.sensiolabs.com
12. ORM
• What is an Entity? It is a regular PHP object
that has been mapped to the Doctrine2 ORM:
/** @Entity */
class User
{
/**
* @Id @Column(type="integer")
* @GeneratedValue
*/
private $id;
/** @Column(type="string", length=255) */
private $name;
public function getId()
{
return $this->id;
}
public function getName()
{
return $this->name;
}
public function setName($name)
{
$this->name = $name;
}
}
Doctrine 2 www.doctrine-project.org www.sensiolabs.com
13. ORM
• No more magic in your domain
• Clean and testable
• Fast!
• Only limited by what you can do with PHP OO
to design your domain
• Inheritance
• Use __construct() without any problems
• Entities are persisted transparently by the
EntityManager
Doctrine 2 www.doctrine-project.org www.sensiolabs.com
14. ORM
• Configure an entity manager to start using
the ORM:
doctrine.orm:
default_entity_manager: default
cache_driver: apc # array, apc, memcache, xcache
entity_managers:
default:
connection: default
Doctrine 2 www.doctrine-project.org www.sensiolabs.com
16. ORM
• Console commands implemented for
improved developer workflow:
• Ensure production settings
• Clear metadata, query and result cache
• Load data fixtures
• Create and drop configured databases
• Generate entities from mapping information
• Generate new skeleton entities
• Generate skeleton entity repository classes
• Convert mapping information between formats
• Convert a Doctrine1 schema
• Import mapping information from an existing database
• Execute DQL and SQL queries
• Create, drop and update database schema from mapping information
Doctrine 2 www.doctrine-project.org www.sensiolabs.com
17. ORM
• Get the default configured entity manager
service:
class MyController extends DoctrineController
{
public function indexAction()
{
$em = $this->getEntityManager();
// ...
}
}
Doctrine 2 www.doctrine-project.org www.sensiolabs.com
18. ORM
• Get a configured entity manager service by its
name:
class MyController extends DoctrineController
{
public function indexAction()
{
$em = $this->getEntityManager('default');
// ...
}
}
Doctrine 2 www.doctrine-project.org www.sensiolabs.com
19. ORM
• Persisting entities is as simple as creating the
object and telling Doctrine to persist it:
class MyController extends DoctrineController
{
public function createAction()
{
$em = $this->getEntityManager();
$user = new User();
$user->setName('Jonathan H. Wage');
$em->persist($user);
$em->flush();
// ...
}
}
Doctrine 2 www.doctrine-project.org www.sensiolabs.com
20. ORM
• Creating Query instances and issue DQL
queries to retrieve objects:
class MyController extends DoctrineController
{
public function indexAction()
{
$em = $this->getEntityManager();
$query = $em->createQuery('select u from MyBundle:User u');
$users = $query->execute();
// ...
}
}
Doctrine 2 www.doctrine-project.org www.sensiolabs.com
21. ORM
• Creating QueryBuilder instances to
programatically build DQL queries through a
fluent interface:
class MyController extends DoctrineController
{
public function indexAction()
{
$em = $this->getEntityManager();
$qb = $em->createQueryBuilder()
->select('u')
->from('MyBundle:User', 'u');
$query = $qb->getQuery();
$users = $query->execute();
// ...
}
}
Doctrine 2 www.doctrine-project.org www.sensiolabs.com
22. ORM
• Update your database schema during
development as your domain model evolves
• Add a new column to our User entity
/** @Entity */
class User
{
// ...
/** @Column(type="string", length=255) */
private $email;
}
Doctrine 2 www.doctrine-project.org www.sensiolabs.com
23. ORM
• Run update command to update your
database schema from mapping information
$ php console doctrine:schema:update
• The above compares your current database
schema to your new mapping information and
executes the necessary queries to bring your
database up-to-date.
Doctrine 2 www.doctrine-project.org www.sensiolabs.com
24. Object Document Mapper
• New Doctrine Project for persisting objects to
MongoDB
• Same architecture as ORM
• Transparently persist PHP5 objects to
MongoDB
Doctrine 2 www.doctrine-project.org www.sensiolabs.com
25. MongoDB ODM
• The DocumentManager
• Central place for persisting and retrieving documents
• Multiple instances allowed
$config = new Configuration();
$config->setProxyDir(__DIR__ . '/Proxies');
$config->setProxyNamespace('Proxies');
$config->setDefaultDB('doctrine_odm_sandbox');
$reader = new AnnotationReader();
$reader->setDefaultAnnotationNamespace('DoctrineODMMongoDBMapping');
$config->setMetadataDriverImpl(new AnnotationDriver($reader, __DIR__ . '/Documents'));
$dm = DocumentManager::create(new Mongo(), $config);
• Dependency Injection handles the creation and
management of document manager services
Doctrine 2 www.doctrine-project.org www.sensiolabs.com
26. MongoDB ODM
• To use the MongoDB ODM you must configure
it:
doctrine_odm.mongodb:
default_document_manager: default
cache_driver: array
document_managers:
default:
connection: mongodb
connections:
mongodb:
server: localhost/somedatabase
Doctrine 2 www.doctrine-project.org www.sensiolabs.com
27. MongoDB ODM
• If the defaults are good enough for you then
you can omit all the previous options:
doctrine_odm.mongodb: ~
Doctrine 2 www.doctrine-project.org www.sensiolabs.com
28. MongoDB ODM
• What is a Document? It is a regular PHP object
that has been mapped to the MongoDB ODM:
/** @Document */
class User
{
/**
* @Id
*/
private $id;
/** @String */
private $name;
public function getId()
{
return $this->id;
}
public function getName()
{
return $this->name;
}
public function setName($name)
{
$this->name = $name;
}
}
Doctrine 2 www.doctrine-project.org www.sensiolabs.com
29. MongoDB ODM
• Get the default configured document
manager:
class MyController extends DoctrineController
{
public function indexAction()
{
$dm = $this->getDocumentManager();
// ...
}
}
Doctrine 2 www.doctrine-project.org www.sensiolabs.com
30. MongoDB ODM
• Get a configured document manager by its
name:
class MyController extends DoctrineController
{
public function indexAction()
{
$dm = $this->getDocumentManager('default');
// ...
}
}
Doctrine 2 www.doctrine-project.org www.sensiolabs.com
31. MongoDB ODM
• Just like the ORM persisting documents is
easy:
class MyController extends DoctrineController
{
public function createAction()
{
$dm = $this->getDocumentManager();
$user = new User();
$user->setName('Jonathan H. Wage');
$dm->persist($user);
$dm->flush();
// ...
}
}
Doctrine 2 www.doctrine-project.org www.sensiolabs.com
32. MongoDB ODM
• Change tracking
– All objects are tracked in an identity map
– Changesets are calculated on flush
– Changesets are used to perform updates using
the atomic operators
• The following code results in an efficient mongo update
with only the properties that need updated:
Array
(
$user->setName('new name');
->
[$set] => Array
(
$dm->flush(); [name] => new name
)
)
Doctrine 2 www.doctrine-project.org www.sensiolabs.com
34. MongoDB ODM
• Query API for building MongoDB queries
through a fluent OO interface:
class MyController extends DoctrineController
{
public function indexAction()
{
$dm = $this->getDocumentManager();
$query = $dm->createQuery('MyBundle:User');
$users = $query->execute();
// ...
}
}
Doctrine 2 www.doctrine-project.org www.sensiolabs.com
35. MongoDB ODM
• Using Query builder API
class MyController extends DoctrineController
{
public function indexAction()
{
$dm = $this->getDocumentManager();
$query = $dm->createQuery('User')
->where('username', 'jwage');
$user = $query->getSingleResult();
// ...
}
}
• where(), whereIn(), whereMod(), whereNot(),
etc.
Doctrine 2 www.doctrine-project.org www.sensiolabs.com
36. MongoDB ODM
• Fluent Query interface generates and
executes find() and findOne() methods
internally
• Query information is collected via fluent oo
interface and executed later
Doctrine 2 www.doctrine-project.org www.sensiolabs.com
43. MongoDB ODM
• Document Query Language (DQL)
– atomic operators
– skip and limit main results
– skip and limit embedded documents
– use dot notation for querying embedded
documents
– embed JSON values in your DQL syntax
$query = $dm->query("update User pushAll groups = '[1, 2, 3]'");
Doctrine 2 www.doctrine-project.org www.sensiolabs.com
44. Database Migrations
• New DoctrineMigrationsBundle contains
integration with the Doctrine Database
Migrations project
• Migrations have been completely re-written
from Doctrine1 and are an extension of the
database abstraction layer
http://www.doctrine-project.org/projects/migrations
Doctrine 2 www.doctrine-project.org www.sensiolabs.com
45. Database Migrations
• Migration classes:
class Version20100416130401 extends AbstractMigration
{
public function up(Schema $schema)
{
}
public function down(Schema $schema)
{
}
}
Doctrine 2 www.doctrine-project.org www.sensiolabs.com
46. Database Migrations
• Manually execute SQL for migrations:
class Version20100416130422 extends AbstractMigration
{
public function up(Schema $schema)
{
$this->_addSql('CREATE TABLE addresses (id INT NOT NULL, street
VARCHAR(255) NOT NULL, PRIMARY KEY(id)) ENGINE = InnoDB');
}
public function down(Schema $schema)
{
$this->_addSql('DROP TABLE addresses');
}
}
Doctrine 2 www.doctrine-project.org www.sensiolabs.com
47. Database Migrations
• Use API of Schema objects to perform
migration:
class Version20100416130401 extends AbstractMigration
{
public function up(Schema $schema)
{
$table = $schema->createTable('users');
$table->addColumn('username', 'string');
$table->addColumn('password', 'string');
}
public function down(Schema $schema)
{
$schema->dropTable('users');
}
}
Doctrine 2 www.doctrine-project.org www.sensiolabs.com
49. Database Migrations
• Execute migration dry runs:
$ ./doctrine migrations:migrate --dry-run
Are you sure you wish to continue?
y
Executing dry run of migration up to 20100416130452 from 0
>> migrating 20100416130452
-> CREATE TABLE users (username VARCHAR(255) NOT NULL, password VARCHAR(255) NOT NULL) ENGINE = InnoDB
• Omit --dry-run to execute migration.
Doctrine 2 www.doctrine-project.org www.sensiolabs.com
50. Database Migrations
• Specify a version number to revert to or 0 to
revert all migrations:
$ ./doctrine migrations:migrate 0
Are you sure you wish to continue?
y
Migrating down to 0 from 20100416130401
-- reverting 20100416130401
-> DROP TABLE users
-- reverted
Doctrine 2 www.doctrine-project.org www.sensiolabs.com
51. Database Migrations
• Write migration SQL file instead of executing:
$ ./doctrine migrations:migrate --write-sql
Executing dry run of migration up to 20100416130401 from 0
>> migrating 20100416130401
-> CREATE TABLE users (username VARCHAR(255) NOT NULL, password VARCHAR(255) NOT NULL) ENGINE = InnoDB
Writing migration file to "/path/to/sandbox/doctrine_migration_20100416130405.sql"
• It would produce a file like:
# Doctrine Migration File Generated on 2010-04-16 13:04:05
# Migrating from 0 to 20100416130422
# Version 20100416130401
CREATE TABLE users (username VARCHAR(255) NOT NULL, password VARCHAR(255) NOT NULL) ENGINE = InnoDB;
Doctrine 2 www.doctrine-project.org www.sensiolabs.com
52. Database Migrations
• Integration with ORM for generating
migrations when you change your mapping
information. Add a new property to your
Entity: /** @Entity @Table(name="users") */
class User
{
/**
* @var string $test
*/
private $test;
// ...
}
• Run the migrations diff command:
$ ./doctrine migrations:diff
Generated new migration class to "/path/to/migrations/DoctrineMigrations/Version20100416130459.php" from schema differences.
Doctrine 2 www.doctrine-project.org www.sensiolabs.com
53. Database Migrations
• The generated migration class looks like:
class Version20100416130459 extends AbstractMigration
{
public function up(Schema $schema)
{
$this->_addSql('ALTER TABLE users ADD test VARCHAR(255) NOT NULL');
}
public function down(Schema $schema)
{
$this->_addSql('ALTER TABLE users DROP test');
}
}
• It contains the SQL statements required to
update your database with the schema
changes.
Doctrine 2 www.doctrine-project.org www.sensiolabs.com
54. Database Migrations
• Run migrate command to execute the
generated migration:
$ ./doctrine migrations:migrate
• Now your database is up to date and contains
the new column named test.
Doctrine 2 www.doctrine-project.org www.sensiolabs.com
55. Questions?
Jonathan H. Wage
jonathan.wage@sensio.com
sensiolabs.com | doctrine-project.org | sympalphp.org | jwage.com
You should follow me on http://www.twitter.com/jwage for updates about Symfony,
Doctrine and related developments.
You can contact Jonathan about Doctrine and Open-Source or for
training, consulting, application development, or business related
questions at jonathan.wage@sensio.com
Doctrine 2 www.doctrine-project.org www.sensiolabs.com