Skip to content

Instantly share code, notes, and snippets.

@ruckus
Last active December 14, 2015 19:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ruckus/5135590 to your computer and use it in GitHub Desktop.
Save ruckus/5135590 to your computer and use it in GitHub Desktop.
RecommendationsController example beforeFilter usage
<?php
class RecommendationsController extends AppController {
private $recommendation;
private $actions_that_require_a_recommendation = array('show', 'edit');
private $actions_that_require_ownership = array('show', 'edit');
function beforeFilter() {
if (in_array($this->action, $actions_that_require_a_recommendation)) {
$this->load_recommendation($this->input->get('recommendation_id'));
}
if (in_array($this->action, $actions_that_require_ownership)) {
$this->check_object_ownership();
}
}
function show {
// we've already loaded up $this->recommendation so
// do whatever you need to do with it
}
private function load_recommendation($id) {
$this->recommendation = Recommendation->find_by_id($id);
if(empty($this->recommendation)) {
throw new FileNotFoundException(); // throw a 404
}
}
private function check_object_ownership() {
$valid = false;
if($this->recommendation->owner_id == $auth->user_id)) {
$valid = true
}
if(!$valid) {
throw new ForbiddenException(); // throw a 401
}
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment