Skip to content

Instantly share code, notes, and snippets.

@mustmodify
Created March 30, 2012 20:02
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • 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";
}
?>
@mustmodify
Copy link
Author

I would like to thank PHP for reminding me of how fortunate I am to be writing Ruby.

@userabuser
Copy link

Thanks for your contribution, always appreciated.

I don't mind Ruby overall but I feel more fortunate to be writing a language, PHP, that feels more like a language, than Ruby which to me looks ugly-ish. Though its a matter of taste quite clearly, that and the fact that I've not worked on that many commercial Ruby projects to have a soft spot for it - yet.

You did a pretty good job at making your gist look ugly as heck.

Instead some simple improvements make a difference...

$a = new User();

if ( $a->can_view('whatever') ) {

   echo "yep\n";

} else {

   echo "as expected, non-admins can't view random stuff\n";

}

Much nicer, easier to understand. (_extra line breaks optional_)

For a nice clean implementation that's easy to understand, checkout...

https://github.com/danieleds/SimpleRoles

...whom was also inspired by CanCan.

Keep up the good work!

ps. I gave you a gold star too ;)

@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