ORM is my favourite part of the MVC framework. It make it so easy to access data anywhere. We use it mainly in the Controller, only sometime inside Model when need to access other model data (e.g. relations) , but seldom in side the view (we can always prepare it in controller and pass it to view).
ORM provide a very handy/ quick syntax to access data in DB base on the model. We can add extra query to filter result, sort result, and it’s very easy to access the other model using relations.
Here’s some example I used ORM in different PHP frameworks.
Yii’s Active Record is powerful and flexible. It support lazy loadingeger loading and custom join with relationship.
In order to handle the MANY_MANY relationship, we need to write explicit update method in relation class, and call this method in the object class.
Named scope is very handy to save time build custom query.
Yii 2
Compared with Yii1, version 2’s syntax is more institued.
like:
Laravel - Eloquent
Eloquent syntax is most institue and easiest to learn in these solutions. But the some of the area is not very flexible, e.g.
Eloquent eager loading example:
And this is how the Eloquent handle the updates for MANY_MANY relationship:
Eloquent’s scope usage:
And the sql generated is not tuned [prove it]
Symfony - Doctrine
While other solutions are using Active Record patern, Doctrine is using Data Mapper patern, it means it will only cater the abstraction in Domain Object, doesn’t know how the objects stored in the database. So it’s lighter, it benefit the automate testing.
近期评论