Where to put sql queries in Yii (or any framework with ORM support)?
This is a more of a coding style question for projects using MVC architecture.
I'm working on a project using Yii framework. Each database table has it's own model class and lets me take advantage of Yii's Active Record stuff. Cool.
But now I need to do an SQL query with a complex logic and a lot of tables being joined. The best and quickest way to do this is to write a raw SQL and put it in some getSomeComplexLogicData
method.
The question is, where do I put this method? Is it a good practice to leave it in a controller where I'm calling it (it's highly unlikely that it will be re-used anywhere else), or should I put it in some Model class that it best corresponds with?
It is not mandatory for Yii's "models" to extend CActiveRecord
.
You can create a simple domain object, which contains the business logic for some structure in your code an have separate mapper for that structure, which contains the complicated SQL queries.
You should try to avoid lumping all in a single class because you end up with SRP violations, which is one of main reason why active record pattern is usually considered to be harmful (there, of course, are some exceptions). It dents to combine bot domain logic and storage logic on single class, thus making it hard to test and maintain.
If you were using a proper MVC or MVC-inspired design pattern, there would be no "models". Model is supposed to be a layer. Not a class or object. And you should no have any domain business logic exposed to controller.
1) You can put this method into components/Controller.php so that this method available for you into each your application controller.
2) Best way is to make a your own component. You can call your compoment from controller, model, views.
Yii::app()->yourcomponentname->methodname
Link to learn how to make component: http://www.yiiframework.com/wiki/187/how-to-write-a-simple-application-component/
链接地址: http://www.djcxy.com/p/60844.html