Zend Framework and Doctrine. Part 1

Posted November 16th, 2009 by Juozas

doctrine-orm-php5If you are following twitter (you can find me there also) or any other social network, you might have noticed that there is a huge interest in Doctrine and Zend Framework integration. Since I’ve been using these libraries for quite a while now, so I’m going to explain some best practices and ways you can do that.

History

To start with, in my opinion, Zend Framework never had a proper M from MVC. It was quite common to use Zend_Db_Table as base models class, but it was simply not practical. When you start dealing with relations and hierarchical data types it starts to get really tricky, because simply Zend_Db_Table doesn’t provide an extensive enough functionality.

So half a year ago Zend Framework developers started to look for better solutions. Quite obvious one was to start implementing their own Domain layer. You can find quite a few different implementations of that in blogosphere, and I chose this path also. However, after quite some time of developing my own code I realized that it’s simply not a right thing to do – I’m expected to deliver a product and I was “wasting” way too much time tweaking, testing, extending etc. my domain model code.

So about 3-4 months ago I completely switched to Doctrine. After evaluating possible solutions I decided to stay with Doctrine for a long time. I don’t know any other solution coming, I definitely don’t want (mainly because I don’t have time) to invest on creating my own library and Doctrine is simply awesome when you get used to it. After all this time I can say that it was a right call – Doctrine is on a way to being officially supported in Zend Framework (Symfony has it right now) and with Doctrine 2.0 (you can see a short presentation of its new features right here) it will be just a perfect tools combination. I would very much agree with Giorgio that:

Thus, Doctrine 2 is going to become the first production-ready Orm for php and to be favored with seamless integration in both Zend Framework and Symfony.

Benefits

Zend framework Some time ago I was actually involved in making a decision of choosing Doctrine over other libraries (main Zend Framework components) as part of my work, so here I’m going to outline some points which made that decision easier.

Relations. I keep repeating this term every time I speak about Doctrine (or ORM’s in general), but for me it’s a key factor in writing code fast. Quick example: let’s image that our application consists of Order which has a list of Items where Item is Product and price, quantity information. Code for this situation:

$order = new Order();
 
$item = new OrderItem();
$item->Product = $product; // product object from somewhere
$item->quantity = 10;
$item->price = 9.99;
 
$order->Items->add($item);
 
$order->save();

This is how much code I need to write myself. I’m going to show more examples in the future posts, but because Doctrine is ORM (object relation mapper) all the hierarchical structure of your application data becomes very easy to work with.

What is more, Doctrine can generate all the model classes by itself. Now that’s a treasure! Just specify database connection in the config file, open up a terminal and run:

php doctrine-cli.php generate-models-db

In a few seconds all schema information is retrieved from the actual database and all the classes are created. My biggest project so far with Doctrine was worth more than 10′000 lines of models code. I don’t know how to count the time it saved and despite a few minor bugs in Doctrine library it worked exactly as we wanted.

I can list things I like about it for hours probably, so I’m going to finish this list with the future I consider to be a very big time saver. This feature is dynamics of models: inheritance and behaviors. Inheritance makes your objects have different classes even though they could be a same table (with for example type_id). All the work needed to handle the actual schema is done in background.

Behaviors work in the same way – one line of code and a model becomes physically undeletable (called soft-delete) or has a separate table to save revisions. Behaviors are very similar to decorators in Zend_Form for example – they are small classes which can be added to the main class to extend its functionality. So in the end your mode could have all sorts of different functionality depending on how you “decorate” it.

What’s next?

I only wrote a few examples how great Doctrine actually is today, but you can expect a lot more. Especially in Zend Framework code side: application.ini settings, application resource to setup auto-loading, script to generate Zend Framework compatible models, testing Doctrine models and much more. I’m also involved in a work group making Doctrine and Zend Framework integration possible so you can expect great things to come (first proposal here).

If you have been following me on twitter you might have noticed that I tweet a lot of interesting material on both Zend Framework, Doctrine and general PHP so I would recommend following me there or subscribing to the RSS feed. I haven’t been writing for a while now, but I will try as hard as I can to change it and write much more frequently – during past months I tried a lot of cool stuff which I would love to talk about.

All parts:

  1. Zend Framework and Doctrine. Part 1
  2. Zend Framework and Doctrine. Part 2
  3. Zend Framework and Doctrine. Part 3

 

Trackbacks/Pingbacks

  1. Zend Framework in Action » Zend Framework and Doctrine
  2. Juozas Kaziukenas’ Blog: Zend Framework and Doctrine. Part 1 | Development Blog With Code Updates : Developercast.com
  3. Juozas Kaziukenas’ Blog: Zend Framework and Doctrine. Part 1 | Webs Developer
  4. Zend Framework and Doctrine. Part 2 | Juozas devBlog
  5. LimeSpace – IT » Der Wochenrückblick: Doctrine, Kunden, Bruce Lee und JQuery
  6. Zend Framework or Doctrine | Candes | Cristian Neagu - UI Designer, Developer, Consultant
  7. Zend Framework University — Blog — Juozas Kaziukenas' Blog: Zend Framework and Doctrine series
  8. Doctrine 1.2 Integration with Zend Framework | Candes | Cristian Neagu - UI Designer, Developer, Consultant - Magento, Drupal
  9. Zend Framework and Doctrine. Part 3 | Juozas devBlog
  10. খবরাখবর: ডিসেম্বর ৪ « পিএইচপি, বাংলায়
  11. Zend Framework Blog » Blog Archive » Aus den Zend Framework Blogs (Spezial: Doctrine und Zend Framework)
  12. Zend Framework + Doctrine + ExtJS « Stevedev Inc.
  13. Integrando o Doctrine no Zend Framework | Fernando Mantoan

Comments (19)

  1. Ben

    Really good first post about this topic! I like the idea of getting my work done with Doctrine and the Zend Framework. Atm the Zend_Db_Table Model thing isn’t the right for me… I’m looking forward to your next posts about this topic!

  2. Richard

    Happy to see you back! Waiting for more interesting articles about frameworks and PHP :)

  3. Giorgio Sironi

    I will help with the integration of Doctrine 2 as much as I can. :)

  4. Nicola Beghin

    I would be interested to know your opinion about CakePHP, a framework which has all of those features built-in from a lot of time. Your articles have always been a huge inspiration about new technologies, so I would really appreciate your view about the subject!

  5. Mario Awad

    Automated integration of Doctrine and Zend Framework Tool is something to look forward to. I subscribed to your RSS feed to stay updated. Cheers :)

  6. Juozas (author)

    Nicola, I google a bit about Doctrine and CakePHP, it seems that it’s possible, although not easily. In manual (http://book.cakephp.org/view/66/Models) it seems that CakePHP has their own models system and I don’t know any way how you can inject Doctrine models. Mainly because you will loose all the additional functionality provided by CakePHP code.

    Thanks all for good comments!

  7. Nicola Beghin

    yes I meant it would be useless to use Doctrine in Cakephp as it already implements the features you talk about from quite a time.
    Do you know cake or know why Doctrine should be used in it?

  8. Juozas (author)

    Problem is – I haven’t used cakephp at all. From what I see – it does provide quite similar functionality to Zend_Db_Table (from 5 min. overview), however I couldn’t find much about how actual models work.

    Doctrine has functions like lazy-loading (where relations are loaded when you needed), different hydrations (you can get result as array, not as objects, to save resources), mutators (auto-md5 for a field) and many more.

    Another advantage – Doctrine is very separate project and it is very serious (and stable) one. Using with CakePHP can be a little bit tricky, but it is probably a better ORM.

    Can you guide me to a good features overview?

  9. Giorgio Sironi

    What, CakePHP let us work with Plain Old Php Objects instead of extending an Active Record base class?

  10. Juozas (author)

    Is that a question or a statement? :)

    I just looked at manual right here and couldn’t find anything other than ActiveRecord (I wasn’t reading the whole manual so I may have missed something)

  11. Giorgio Sironi

    It is indeed a question in response to:
    “yes I meant it would be useless to use Doctrine in Cakephp as it already implements the features you talk about from quite a time.
    Do you know cake or know why Doctrine should be used in it?”
    :)

  12. luke

    nice post. I’ve run into issues using the out-of-the-box Zend_Db_Table classes and Doctrine looks like a solid and mature alternative. will stay posted on it.

  13. dustin

    I wrote a tutorial a while back on getting package-based autoloading going with Doctrine, which allows you to have Zend-type naming conventions for your models.

    Check it out at:
    http://dustint.com/archives/137

  14. Juozas (author)

    dustin, very cool! Although now Doctrine (1.2 beta) supports proper classes names and folders structure generation so there is no need to dive into packages.

    I will post generation code and app resource this week.

  15. Mihai Brehar

    Hi,

    I’ve tried using Doctrine and eventually I gave up. It is too slow and eats a lot of memory.

    I guess the memory problem is not really Doctrine’s fault because PHP cannot garbage collect cyclic references. And Doctrine is making heavy use of that. Sure, PHP 5.3 solves this problem but it will be a long time till wide adoption.

    I’ve found a workaround which is looking like this:
    $manager->setAttribute(‘auto_free_query_objects’, true);

    However, the problem with being slow does not go away and I did not have the time to investigate.

    I was just doing some XML export for 50k rows and the script using Doctrine takes about 15x more time.

  16. Juozas (author)

    Hi, Mihai,

    yes, it’s a known fact, but there many ways how you can avoid this problem (I’ve done export/import with thousands of items myself).

    Firstly, you need understand how Doctrine works. How can you expect it to give you objects (from database) without overhead? This is impossible. If you want to get results efficiently – use array hydration. You can use scalar hidration if you wan’t even more speed, or can even get them straight from PDO – it’s up to you to design the code.

    Doctrine is not slow literally. It’s slower than having an array of data because it’s just how things work – if you want nice hierarchical objects you have to construct them somehow, hence there is a overhead.

    I’m going to write more about performance concerns, but basically if you measure things like “slow” properly (using profiling for example) and don’t just think that Doctrine is slow, you can get amazing results. Turn on query cache, get 5.3, add free up of resources and it runs smoothly.

  17. Mihai Brehar

    Hi Juozas,

    Sure, I expect an overhead, but Doctrine’s overhead is too much in my opinion. By using array hydration I loose a lot of features, and it’s because of the features that I tried Doctine in the first place.

    You are right, it’s all about how you design the code. Maybe there is a fast and low footprint way to use Dotrine. I just did not have the time to find it.

    I am looking forward for your next articles on performance.

    Regarding PHP 5.3, I’ll wait some time before using it in production.

  18. Juozas (author)

    Hi Mihai,

    I had the same issues, but it’s just how things work. At some point you need to agree, that it’s physically impossible to hydrate more faster without using extension (Doctrine has plans for that) or some other low level code. Because all the overhead basically comes from iterating over big array and setting each value to an object property.

    At least I don’t know any better hydrations (in PHP) and for parts where I need a lot of results I always use arrays or chunked/on-demand hydrators. I’m going to write about these more.

    I do agree that Doctrine is sometimes too much, but I still use it because of all advantages it gives me. Some related info is here too: http://www.doctrine-project.org/blog/php-benchmarking-mythbusters.

    Speaking of 5.3, if you have an option – switch to it. Doctrine runs faster, Zend Framework runs faster (and uses less memory) and very stable (using it in production right now).

  19. dave

    think for your article
    I’m exactly in the same way : coming from Java, I choosed Php Zend and, after begin my own model, choosed Doctrine. I think the tow can be powerful. Now I have to integrate them ! ^^

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">