I’have been using Yii for quite some times (around 3 years) and I really like this framework, but one thing always bothered me, is the way we retrieve complex data from the db.
In général in Yii we have 2 solutions when we want to fetch some data:
In the controller we create a custom query
$criteria = new CDbCriteria;
$criteria->order = "name desc";
//Some other complex criteria
$post = Post::model()->findAll($criteria);
//rest of the controller action
In the model we create a method like “findAllOrderedByName” that retrieve the data ordered by it’s name.
The custom query in the controller is not good because we shouldn’t have some db related operations in the controller. So we put it in the model, but if we have a lot of custom queries, the model become really big and we have a mix between the model characteristics (its attributes, relations, rules, …) and the way we fetch the data.
For this Symfony is using Repository classes. This is a class that will store all the custom queries that could be performed on a model. For example for the class Post we’ll have the class PostRepository that will store the “findAllOrderedByName”.
I really like this idea and I was wondering if someone already used this approach in a Yii project.
Do You tried to use parameterized scope inside the model? When I have complex querys or I need to use in more then a controller, I used to use parameterized scope inside the model:
Yeah but a parameterized scope in the model doesn’t solve my problem, the model will still hav a lot of information on the way to retrieve the model and for me, the model is not the right place to have it.
What I’d like would be to have in the model only the relations, the rules, and the attributes. But for the rest use another class.
This is kind of apply the repository pattern in Yii. (I say kind of because yii is using Active Record pattern)
The repository class makes a lot of sense, but is there anything in Yii that’s preventing you from following that pattern? As far as I can see, you just need to create classes with a bunch of static methods to perform each specific request.
Yes, I was about to write the same thing. There is nothing here that prevents you from creating the similar mechanism. In most cases it’s overkill and I think this is main reason Yii doesn’t have something like it.