TIP: Use Markdown or, <pre> for multi line code blocks / <code> for inline code.
Validating image uploads and resizing the right way
  • So, I've got at least 3 "solutions" to validate, crop/resize/do whatever and than save images.

    The problem is that models aren't the right place to do it, controllers get ugly and confusing when doing it and there's not proper way of image validation.

    If you had "articles" table with a "image" field that should containt one image name, how would you handle "new article" / "edit article" validation? ( Not only "upload must be max 1M size and jpg or png, but with resizing / cropping )
  • This sounds like model-specific functionality, so my first guess is to put it in the model.

    What you could do, is create some helper classes that allow for easy validation/resizing/cropping from within the model or as a callback in the validation
  • I personally keep it in the model... Your models are application data, not just database data. There is no necessity for there to even be a database behind your models.. it could be flat file per record, XML, or whatever.. Uploaded files are just more application data...

    I override __get() to catch the image (which I expect to be set to $_FILES['']).. I'll then process the image, save it to a temporary location, and if successful, set some metadata columns (like image_size, image_name, image_type etc). I then validate the metadata fields as part of check(), which I extend to, on success, move the temp file, and on failure, delete the temp file.).

    There are probably better ways to do this though!
  • @kiall I usually have a method for image formatting in the model, without attaching it to $_FILES since it would pretty much fail unit tests;

    http://pastebin.com/MFZiKYJM

    This way I do have to validate upload itself in the controller (if image is being uploaded), but it still allows me to pass it some tmp path of the file which I got with file_get_contents() or whatever. Any suggestions are welcome