Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.