Currently playing with the Laravel php framework.
It’s been said by many already, it’s a really cool framework. Well designed and documented. Coming from a CodeIgniter background, it’s easy to jump in and refreshing to get all the new cool features.
The Eloquent ORM has a nice minimalist approach to writing database abstraction. If you’re coming from Propel or Doctrine it’s crazy how little you actually need to get Eloquent going.
Eloquent supports relationships between models out of the box, like so:
class Post extends Eloquent {
public function comments()
{
return $this->has_many('Comment');
}
}
Very simple.
What if I need to add conditions to that relationship?
For instance, I’ve got a system with lot of meta info. Multiple tables have meta data.
Rather than having a meta table for each entity I would rather have a single meta table with a (target_type / target_id) set of columns.
The target_type column is the table it refers to and target_id the id in that table. (so for users, target_type='users', target_id = <some_user_id>)
To load meta info for any entity as a One-To-Many relationship, Laravel would automatically link the target_id for me but I would also need to enforce the target_type field in the relationship (otherwise I may load meta data from other entities).
It’s actually quite easy to do in Laravel.
The has_many method returns the relationship object itself (not the actual data, you still need to call get() on it).
What that means is that you can call additional methods on it before returning it.
Looking at the class hierarchy, relationships are actually subclasses of Query so you can call the usual Eloquent filtering methods on it.
Here’s how it would work for a User->Meta relationship:
class User extends Eloquent {
public function meta()
{
return $this->has_many('Meta','target_id')->where('target_type','=',$this->table());
}
}
Too easy.