File and Image manipulation - model or controller?


it’s not exactly an yii question, but more mvc. I have some ar models with file and image fields and I just wondered where to handle the file upload and image manipulation - in the controller or in the model, what is the best practice? I prefer to do it in the model, because I have to upload and manipulate files for one model in several controllers, but in all tutorials the file is uploaded in the controller.

Thank you,


Usually, the best practice for that kind of operation is to write it in the controller.

But it is just a best practice, not a rule. The focus should be on solving the problem.

Maybe the best solution is to have a library in the form of an extension, behavior or other component that can be used from your controllers.

A possible, reusable solution: Create an application component that does the actual job of transforming and saving/deleting files. Save paths and transformation parameters can be configured in application’s config file as properties of the component. Then write a model behavior that handles onBeforeSave and onBeforeDelete events via this application component.