Created
March 30, 2012 20:02
-
-
Save mustmodify/2254515 to your computer and use it in GitHub Desktop.
How to implement URP in PHP using a cancan-style interface
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 User | |
{ | |
public $admin; | |
public $roles = array(); | |
function roles() | |
{ | |
if (isset($this)) | |
{ | |
return $roles; | |
} | |
else | |
{ | |
return array('admin', 'manager', 'rep', 'customer', 'user'); | |
} | |
} | |
function has_role( $needle ) | |
{ | |
foreach ($this->roles as $role) | |
{ | |
if($role == $needle) | |
{ | |
return true; | |
} | |
} | |
return false; | |
} | |
function can_view($entity) | |
{ | |
if( $this->has_role('admin') ) | |
{ | |
return true; | |
} | |
else | |
{ | |
if( $entity == "thing" && $this->has_role('manager') ) | |
{ | |
return true; | |
} | |
else | |
{ | |
return false; | |
} | |
} | |
} | |
function can_edit($entity) | |
{ | |
} | |
function can_delete($entity) | |
{ | |
return false; | |
} | |
function can_manage($entity) | |
{ | |
} | |
} | |
$a = new User(); | |
if( $a->can_view('whatever') ) | |
{ | |
echo "yep\n"; | |
} | |
else | |
{ | |
echo "as expected, non-admins can't view random stuff\n"; | |
} | |
array_push($a->roles, 'admin'); | |
if( $a->can_view('whatever') ) | |
{ | |
echo "as expected, admins can view anything."; | |
} | |
else | |
{ | |
echo "uh oh"; | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@mustmodify thanks for this, and I should say, writing more Ruby is making me like PHP more -- just saying.