I am just about to undertake building a relatively large PHP system, I just need some ideas on how to implement a certain feature.
I will allow users to register. Onc开发者_如何学Ce registered, the user will have a security level which will be assigned to their account.
So if I had security levels 1, 2 and 3, what would be the best way to show certain things to people with certain security levels ?
Thank you in advance.
Before you reinvent the wheel, be sure to look whether Zend_ACL is for you. I haven't used it myself but from what it promises in the docs, it can do what you need and much more.
Pekka's comments about looking at the Zend API's are good. Many of the Frameworks for PHP are currently (sadly) badly implemented junk (with hideously amateur code underneath), but the Zend API's are almost uniquely valuable.
If you do roll your own, which there is nothing wrong with doing if you can't find something that fits what you want (and can't be extended easily), then I'd take an OO approach and expose user properties via a class.
e.g.
$user = new User($session->userId);
if (!$user->isAdministrator && !$user->canViewReports)
someErrorHandler("You do not have permission to access this content.");
I'd avoid having fixed levels, but instead follow a roles based approach.
i.e. I'd avoid having levels like:
- Staff
- Manager
- Administrator
And instead I'd go for properties (just as illustrative examples):
- read_access
- write_access
- can_view_logs
- can_view_reports
- is_administrator
This allows you to be easily more explicit later, when you (inevitably) discover you want an additional permissions group you want have to go back and change existing code.
That doesn't mean putting users in groups is a bad idea (it's not and you could implement this using a groups system, e.g. where by a user could be in both "Reporting" and "Logs"), but assumptions about security levels being hierarchical are typically the wrong approach (e.g. Level 1=Staff, Level 2=Managers, Level 3=Admin) - this is because you almost always end up needing a system that's more flexible than a simple hierarchical system allows.
In practice if you do end up taking this approach, you may want to have a Permissions or Group class, to avoid having an overly large User class (which might end up full of stuff for getting user properties, setting new passwords, etc).
e.g.
$group = new Group($session->userId);
if (!$group->Administrators && !$group->Reporting)
someErrorHandler("You do not have permission to access this content.");
精彩评论