Doctrine, MySQL and Zend_Date

by jon on August 10, 2008

Something that I've found really helpful in C# is the DateTime object and how it can be natively mapped to NHibernate classes and then straight to the database.

The equivalent Doctrine code is almost as elegant. Here's an excellent example of when objects abstract you from the nitty-gritty string parsing code that would be required to do time-stamping in a database:

 
$today = new Zend_Date();
$newPost = new Post();
 
$newPost->title = 'posting for ' . $today->get(Zend_Date::TIME_MEDIUM);
$newPost->createdAt = $today->get(Zend_Date::W3C);
$newPost->save();
 

Zend_Date::W3C returns a W3C compliant timestamp, which the Doctrine Model then passes to the underlying persistence layer.

Assuming that you had a UnitOfWork class handling your persistence, you could add createdAt to all of the YAML models, and have every record stamped with updatedAt and createdAt without changing any higher level code.

Why Bother With UpdatedAt and CreatedAt?

having these two columns in a table can save tremendous amounts of time sorting out concurrency issues. They also allow you to do some very primitive reporting on your data at no cost to adding complexity to the rest of your application.

My Doctrine Model was configured using a YAML file:

 
Post:
  tableName: post
  columns:
    id:
      primary: true
      autoincrement: true
      type: integer(4)
    createdAt: date
    title: string(255)
 

Then it's just a matter of running './doctrine rebuild-db' from the command line from the Doctrine directory and it create's the PHP classes and prepares the database columns.

Using Zend_Date, you can easily do date comparisons, generate different date formats, do complex date querying and so on without having to get into the string / number manipulations.

{ 3 comments… read them below or add one }

LeisureLarry October 9, 2008 at 7:46 am

Another possibility which I would prefer is to use doctrine templates. For example my doctrine test model is configured using the following YAML file:


User:
tableName: users
actAs:
Timestampable:
created:
name: created_at
type: timestamp
format: Y-m-d H:i:s
updated:
name: updated_at
type: timestamp
format: Y-m-d H:i:s
options:
type: INNODB
charset: utf8
columns:
id:
primary: true
autoincrement: true
unsigned: true
notnull: true
type: integer(11)
first_name:
type: string(255)
notnull: true
last_name:
type: string(255)
notnull: true
email:
type: string(255)
notnull: false
password:
type: string(255)
notnull: true

jon October 9, 2008 at 2:02 pm

LeisureLarry,

This looks great. I’m not familiar with Doctrine templates. Does this mean that you don’t even need to write any code to handle time-stamping records?

Doctrine continues to impress me.

LeisureLarry October 9, 2008 at 3:50 pm

Yes, you don´t need to write any code except these yaml actAs entries.

Greats from Germany
LeisureLarry (interiete.net)

Leave a Comment

Previous post:

Next post: