Skip to content

Instantly share code, notes, and snippets.

@mustmodify
Created March 30, 2012 20:02
Show Gist options
  • Save mustmodify/2254515 to your computer and use it in GitHub Desktop.
Save mustmodify/2254515 to your computer and use it in GitHub Desktop.
How to implement URP in PHP using a cancan-style interface
<?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";
}
?>
@deletosh
Copy link

@mustmodify thanks for this, and I should say, writing more Ruby is making me like PHP more -- just saying.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment