I would like to know which one of the following is the best choice for O/R mapping in PHP:
Axon
CakePHP
Doctrine
Kohana PHP
lworm
PdoMap
Propel
Rocks
Qcodo
Redbean
Sphorm
Torpor
We are going to use PHP only for Web Service implementation. We have a Java background so a framework which is inspired by Hibernate would be easier for us to use as long as it's a good, well documented and more or less easy to use O/R mapping library.
Thank you!
The problem with this question is that it is hard to tell what is the best choice for your specific task and environment. Furthermore, a full comparison would require in-depth knowledge of all the alternatives.
As for Doctrine you'll be able to find a good piece of documentation. And it is fairly easy to get going.
Like Jensgram already notes, it is hard to tell which option suites your needs.
That said, I have experience with Kohanaphp and it's integrated ORM. I must say it works perfect, but it has limited functionality if you compare it to Doctrine2. If you need advanced options like inheritance mapping and proxy classes Doctrine is the way to go. Like Doctrine 2 introduction says:
Object relational mapper (ORM) for PHP
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.
As it says, it is inspired on Hibernate HQL. I don't have experience with the other options you mention, so I can't say anything usefull about those.
I used to write the data access functionalities in model itself. Now I want to separate data access from business logic. I am using codeigniter as framework.
It seems that one way of doing it is use ORM, but it will have a performance penalty I guess.
are there any general best practices?
Have a look at POEAA's Data Source Architectural Patterns:
Table Data Gateway
Row Data Gateway
Active Record
Data Mapper
CodeIgniter claims to use ActiveRecord, but it doesnt. It's more like a rudimentary QueryObject. To truly separate your DAO from your Domain objects, you have to use a DataMapper. Depending on the complexity of your mapping needs you can build one yourself or use an ORM. Ironicaly, the majority of ORMs in the PHP World are based on ActiveRecord, which is pretty ill-suited for ORM. Doctrine 2 is the only I know that uses a DataMapper approach.
An ORM will always come with a performance penalty (and it can be a serious one). However, you should not rule out an ORM just because of that. Handcrafting an efficient DataMapper in a high impedance mismatch scenario can be tedious and difficult work. Again, see POEAA for a list of common Object-Relational patterns.
There seems to a DataMapper implementation for CodeIgniter with Overzealous DMZ. I have never worked with it and cannot say anything about it. It just came up after a quick google, so I thought I add it here.
I'm currently on my way to write a web application implementing the MVC and well reducing complex things. Yet I've been pondering for a few hours what to do for future database systems like Oracle, PostgreSQL, Firebird, etc.
Then again to implement these adapters in the logic is what gets me, should I just trigger-happy it with tons of SWITCHes? What can I do in this situation?
The typical answer to this is to use the ORM functionality in your framework. You can either treat your models as dataobjects or you could use some composition and let models have data objects. Either way, your data objects should be fairly abstract and mainly compile DB queries queries using methods - like the Zend framework does it with the Select object. This allows you to a) keep sql out of your objects and b) replace the objects that actually produce your sql.
So, if you data objects all inherit from the same base ORM class, this base class can be given a DB object that it sends queries to. If you swing it right, the ORM base class will be ignorant of the type of DB class: the data object compiles a select object and hands it over to the DB object that then interprets it in whichever way it finds best.
And the short answer: no, don't use a bunch of switch statements :)
Yet I've been pondering for a few hours what to do for future database systems like ...
You’re NOT gonna need it!
If you want a lightweight ORM for PHP, I'd look at Outlet. It should work with any standard PDO database type.
I would avoid ORM layers here is what Drupal developers have to say about
http://www.garfieldtech.com/blog/orm-vs-query-builders
I've currently got a site that depends on an Active Record pattern using the Doctrine ORM in PHP. I'm generally a fan of this approach - it's very straightforward and works well for managing for simple CRUD apps. But as this site grows, I think my need for more robust domain functionality will grow as well. I was wondering what other kinds of data design patterns work well in conjunction with an ORM.
My basic problem right now is that Doctrine seems to work best as a fancy querying language, so my models are littered with methods like:
function getBySomeClassfication($classification)
{
return Doctrine_Query::create()
->select('stuff')
->from('ModelClass')
->where('something = ?', $classification)
->execute();
}
or if I want to access a model class directly:
Doctrine::getTable('ModelClass')->findAll();
This means I end up working with Doctrine's object wrappers instead of directly on my domain objects. I feel like all this should exist at a lower level of abstraction.
I'm just not quite sure what the best approach is. I feel like the ORM is an excellent layer for querying single tables and dealing with relationships. But I'd like to have more flexibility in creating domain objects that work across multiple models/tables.
I've read up on using the Repository pattern, but still have a few hesitations:
I don't want to just create a pointless layer of abstraction that simply bubbles up the original problem.
I don't want to re-create or render useless the whole point of using an Active Record ORM.
Any thoughts or suggestions?
You need to work with the object wrappers (Data Access Objects) at some point and at some point your calls will be implementation (here Doctrine-) specific. It mainly depends on your current architecture on how many layers you want to put in between, but I would say - as less as possible. Is there any specific problem you have that Doctrine doesn't solve?
I sometimes don't see the point in having to deal with database specifics (e.g. one Domain Entity spreading over several tables) at all when using the ORM as a tool for (from scratch) Object Oriented Domain Model development.
I recently answered a more Java specific question here, but maybe it helps you, too for the architecture idea.
You might have a look at the Zend Framework ORM implementation(if you haven't already) where it is also possible to define relationships across multiple tables.
I hope that helps.
This question's answers are a community effort. Edit existing answers to improve this post. It is not currently accepting new answers or interactions.
Is there a good object-relational-mapping library for PHP?
I know of PDO/ADO, but they seem to only provide abstraction of differences between database vendors not an actual mapping between the domain model and the relational model. I'm looking for a PHP library that functions similarly to the way Hibernate does for Java and NHibernate does for .NET.
Look into Doctrine.
Doctrine 1.2 implements Active Record. Doctrine 2+ is a DataMapper ORM.
Also, check out Xyster. It's based on the Data Mapper pattern.
Also, take a look at DataMapper vs. Active Record.
Try RedBean, its requires:
No configuration
No database (it creates everything on the fly)
No models
etc.
It even does all the locking and transactions for you and monitors performance in the background. (Heck! it even does garbage collection....) Best of all... you don't have to write a single... line of code... Jesus this, ORM layer, saved me ass!
There are only two good ones: Doctrine and Propel. We favor Doctrine, and it works well with Symfony. However if you're looking for database support besides the main ones you'll have to write your own code.
Axon ORM is part of the Fat-Free Framework - it features an on-the-fly mapper. No code generators. No stupid XML/YAML configuration files. It reads the database schema directly from the backend, so in most CRUD operations you don't even have to extend a base model. It works with all major PDO-supported database engines: MySQL, SQLite, SQL Server/Sybase, Oracle, PostgreSQL, etc.
/* SQL */
CREATE TABLE products (
product_id INTEGER,
description VARCHAR(128),
PRIMARY KEY (product_id)
);
/* PHP */
// Create
$product=new Axon('products'); // Automatically reads the above schema
$product->product_id=123;
$product->description='Sofa bed';
$product->save(); // ORM knows it's a new record
// Retrieve
$product->load('product_id=123');
echo $product->description;
// Update
$product->description='A better sofa bed';
$product->save(); // ORM knows it's an existing record
// Delete
$product->erase();
Most of all, the plug-in and accompanying SQL data access layer are just as lightweight as the framework: 14 KB (Axon) + 6 KB (SQLdb). Fat-Free is just 55 KB.
I've been developing Pork.dbObject on my own. (A simple PHP ORM and Active Record implementation)
The main reason is that I find most ORMs too heavy.
The main thought of Pork.dbObejct is to be light-weight and simple to set up. No bunch of XML files, just one function call in the constructor to bind it, and an addRelation or addCustomRelation to define a relation to another dbObject.
Give it a look: Pork.dbObject
Try Doctrine2. It's probably the most powerful ORM tool for PHP. I'm mentioning it separately from Doctrine 1, because it's a completely different piece of software. It's been rewritten from scratch, is still in beta phase, but it's usable now and developed.
It's a very complex ORM, but well designed. Lot of magic from original Doctrine 1 disappeared. It provides a complete solution, and you can write your own ORM on top of Doctrine2 or use just one of its layers.
I just started with Kohana, and it seems the closest to Ruby on Rails without invoking all the complexity of multiple configuration files like with Propel.
I really like Propel, here you can get an overview, the documentation is pretty good, and you can get it through PEAR or SVN.
You only need a working PHP5 install, and Phing to start generating classes.
Check out Outlet ORM. It is simpler than Propel and Doctrine and it works similar to Hibernate, only with more of a PHP feel to it.
I found ORM related classes in the PHP library Flourish.
You should check out Idiorm and Paris.
Give a shot to dORM, an object relational mapper for PHP 5. It supports all kinds of relationships (1-to-1), (1-to-many), (many-to-many) and data types. It is completely unobtrusive: no code generation or class extending required. In my opinion it is superior to any ORM out there, Doctrine and Propel included. However, it is still in beta and might change significantly in the next couple months. http://www.getdorm.com
It also has a very small learning curve. The three main methods you will use are:
<?php
$object = $dorm->getClassName('id_here');
$dorm->save($object);
$dorm->delete($object);
I am currently working on phpDataMapper, which is an ORM designed to have simple syntax like Ruby's Datamapper project. It's still in early development as well, but it works great.
I have had great experiences with Idiorm and Paris. Idiorm is a small, simple ORM library. Paris is an equally simple Active Record implementation built on Idiorm. It's for PHP 5.2+ with PDO. It's perfect if you want something simple that you can just drop into an existing application.
Tried the ORM of Flourish library.
Until PHP 5.3 release don't expect to have a good ORM. It's a OO limitation of PHP.
My friend Kien and I have improved upon an earlier version of an ORM that he had written prior to PHP 5.3. We have essentially ported over Ruby on Rails' Active Record to PHP. It is still lacking some key features we want such as transactions, composite primary key support, a few more adapters (only MySQL and SQLite 3 work right now). But, we are very close to finishing this stuff up. You can take a look at PHP ActiveRecord with PHP 5.3.
Try PHP ADOdb.
I can't say it's the best, because I haven't used the others. But it's fast, it supports Memcached and caching.
And it's waaaay faster than Zend Framework's DB/Select.
Have a look at the LEAP ORM for Kohana. It works with a bunch of databases, including DB2, Drizzle, Firebird, MariaDB, SQL Server, MySQL, Oracle, PostgreSQL, and SQLite. With a simple autoload function, it can work with almost any PHP framework. The source code is on GitHub at https://github.com/spadefoot/kohana-orm-leap. You can checkout LEAP's tutorials online.
The ORM library works with non-integer primary keys and composite keys. Connections are managed via a database connection pool and it works with raw SQL queries. The ORM even has a query builder that makes building SQL statements super simple.
Brazilian ORM: http://www.hufersil.com.br/lumine. It works with PHP 5.2+. In my opinion, it is the best choice for Portuguese and Brazilian people, because it has easy-to-understand documentation and a lot of examples for download.
You can check out Repose if you are feeling adventurous. Like Outlet, it is modeled after Hibernate.
It is still very early in its development, but so far the only restrictions on the domain model are that the classes are not marked final and properties are not marked private. Once I get into the land of PHP >= 5.3, I'll try to implement support for private properties as well.
If you are looking for an ORM that implements the Data Mapper paradigm rather than Active Record specifically, then I would strongly suggest that you take a look at GacelaPHP.
Gacela features:
Data mapper
Foreign key mapping
Association mapping
Dependent mapping
Concrete table inheritance
Query object
Metadata mapping
Lazy & eager loading
Full Memcached support
Other ORM solutions are too bloated or have burdensome limitations when developing anything remotely complicated. Gacela resolves the limitations of the active record approach by implementing the Data Mapper Pattern while keeping bloat to a minimum by using PDO for all interactions with the database and Memcached.
MicroMVC has a 13 KB ORM that only relies on a 8 KB database class. It also returns all results as ORM objects themselves and uses late static binding to avoid embedding information about the current object's table and meta data into each object. This results in the cheapest ORM overhead there is.
It works with MySQL, PostgreSQL, and SQLite.
Agile Toolkit has its own unique implementation of ORM/ActiveRecord and dynamic SQL.
Introduction: http://agiletoolkit.org/intro/1
Syntax (Active Record):
$emp=$this->add('Model_Employee');
$emp['name']='John';
$emp['salary']=500;
$emp->save();
Syntax (Dynamic SQL):
$result = $emp->count()->where('salary','>',400)->getOne();
While Dynamic SQL and Active Record/ORM is usable directly, Agile Toolkit further integrates them with User Interface and jQuery UI. This is similar to JSF but written in pure PHP.
$this->add('CRUD')->setModel('Employee');
This will display AJAXified CRUD with for Employee model.
NotORM
include "NotORM.php";
$pdo = new PDO("mysql:dbname=software");
$db = new NotORM($pdo);
$applications = $db->application()
->select("id, title")
->where("web LIKE ?", "http://%")
->order("title")
->limit(10)
;
foreach ($applications as $id => $application) {
echo "$application[title]\n";
}
Look at http://code.google.com/p/lworm/ . It is a really simple, but powerful, lightweight ORM system for PHP. You can also easily extend it, if you want.
Another great open source PHP ORM that we use is PHPSmartDb. It is stable and makes your code more secure and clean. The database functionality within it is hands down the easiest I have ever used with PHP 5.3.
Doctrine is probably your best bet. Prior to Doctrine, DB_DataObject was essentially the only other utility that was open sourced.
If you are looking for an ORM, like Hibernate, you should have look at PMO.
It can be easily integrated in an SOA architecture (there is only a webservice classe to develop).
A really good simple ORM is MyActiveRecord. MyActiveRecord documentation. I have been using it a lot and can say it's very simple and well tested.