Monday, February 22, 2010

CakePHP & User Uploads

The first time i tackled this problem i did the obvious thing, and placed the uploaded files in the webroot folder inside of the app folder. However the key problem with this is that you lose the ability to quickly move the app folder around without fear. This is important for me, as sometimes i'm working with bargin basement hosting, so "cap depoly" isn't always an option. Leaving the quickest way to deploy to simply replace the entire app folder via FTP. (We all have to start somewhere!)

Thankfully cakes media views allow you to specify a folder anywhere on the webserver!

What i decided to do was to make a simple controller called media and route all of my USG images through it.



class MediaController extends AppController {
/**
 *
 * @var string
 * @access public
 */
var $name = 'Media';

var $uses = array();

/**
 * Index action.
 *
 * @access public
 */
function index( $file = null, $size = 's'  ) {

$this->view = 'Media';

$components = split('\.',$file);

$params = array(
'id'=> $components[0],
'name'=> $components[0],
'extension'=> $components[1],
'path' => ROOT . DS. 'media' . DS .'filter'. DS . $size .DS . 'transfer' . DS . 'gen' . DS
);


$this->set($params);

}

}


So the controller looks a little something like this in it's raw form. I'm using the Media plugin, hence the addition folder paths. The key thing to note is the 'Path' key/val pair in the $params array. Notice you can pass an absolute file path! so in theory you could even mount another drive, and serve your media from there, pretty awesome.

This way, i can use a url like this

example.com/media/filename.jpg/l


To get a large image, and

example.com/media/filename.jpg/s


And this to get a small image.

Quite handy!

No comments: