Last active
December 14, 2015 19:19
-
-
Save ruckus/5135590 to your computer and use it in GitHub Desktop.
RecommendationsController example beforeFilter usage
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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