I’m having a problem understanding the difference between component, utility and behavior.
I read the Cookbook, but it helped me only partly.
For example – I want to resize/crop images on upload.
I will use a number of different forms related to different models and controllers/actions.
Obviously I need to write a class with scale, resize, saveImage and other helpful methods.
I also need the ability to use this methods from different places.
My question is – where is the right place to put this code? And can someone provide me some simple examples about core difference between component, utility and behavior? Because for me components and utilities looks very similar.
The major difference between Utilities and Behaviors/Components is that Utility classes don’t extend a core MVC class, and thus don’t automatically receive hooks into their parent class’s request cycle. For example, in a Component, you could implement a
beforeRender()function that would get called before the controller renders its layout/views, automatically, every time that controller gets called.Also, Utility classes must be instantiated and assigned to a variable before use:
$myUtil = new MyUtility(); $myUtil->blah()— Behaviors/Components/Helpers get instantiated when they’re loaded into a class and can be referenced with$this->MyComponent->blah().In your case, the image manipulation logic would most likely belong in either a Component or a Utility class, and you can choose to implement it either way. Personally, I would go with writing a Component since you’re unlikely to utilize the image manipulation logic outside of your Controllers.
Edit: You might also consider finding and using an existing component that someone has already written, for example I found ImageTool, Image Resizer, Image Upload & Resizer, and Thumbnail in about 2 minutes of Google searching.