Django is a really powerful web framework and I really miss some of it’s gems back in CakePHP. The thing I really miss is get_object_or_404 which is a shortcut for looking up database results and raising a 404 if none are found. When working with Cake most people typically do the following:
function view($id=null) {
if (!$id) {
$this->Session->setFlash(__('Invalid Category.', true));
$this->redirect(array('action'=>'index'));
}
$this->set('category', $this->Category->read(null, $id));
}
So basically, if the read method doesn’t return anything, you get a blank page. Of course, you can check if something was returned or not. But it’s just extra work (and the console should do it for you if you ask me..). So why not make our own get_object_or_404 method?
The easiest way to do this is to create our own method in the AppModel class. Open up app_model.php in your project/app root (or create one if you don’t have it).
<?php
class AppModel extends Model {
function getDataOr404($id = null) {
if(!$id) {
// return a 404 if the ID wasn't supplied
$this->cakeError('error404');
}
$data = $this->read(null, $id);
if($data) {
return $data;
} else {
// $this->read returns FALSE if no data is found
$this->cakeError('error404');
}
}
}
?>
So how do you use this? Open up one of your controllers and do the following:
function view($id=null) {
$this->set('category', $this->Category->getDataOr404($id));
}
Tags: CakePHP
would it not be better to just do your own read method in app controller?
class AppModel extends Model
{
function read( $fields = null, $id = null)
{
if( !$id )
{
// return a 404 if the ID wasn’t supplied
$this->cakeError( ‘error404′ );
}
$data = parent::read(null, $id);
if( empty( $data ) )
{
$this->cakeError(‘error404′);
}
return $data;
}
}
this way you would not have to do and redo all your code.
@dogmatic69 Yes, that also works, but I just went the way Django has it