Я работаю над приложением PHP, и я хотел бы добавить управление доступом к некоторым моим объектам. Я не отмечал этот вопрос как PHP, поскольку я чувствую, что этим вопросом не является конкретный язык.
Скажите, что у меня есть 'Класс обслуживания'
abstract class Service {
}
Многие сервисы используют это в качестве базового класса. Один псевдо пример был бы:
class Companies extends Service {
function getCompanyInfo($id) {
//...
}
}
Позже в будущем я хочу добавить управление доступом. Примером 'getCompanyInfoById' метод является операция 'чтения', таким образом, это потребовало бы полномочия 'чтения'.
В этой точке я могу реализовать это следующим образом:
Недостатки для каждой опции:
Там лучшие пути состоят в том, чтобы приблизиться к этому в целом?
Другим решением может быть небольшой вариант вашего 1.
пример
class Service
{
var $ACL = //some hash map with acl
}
class Companies extends Service
{
function getCompanyById($id)
{
//real code
}
}
class SafeCompanies extends Companies
{
//If a method must be "protected" with an ACL, you must override them in this way
function getCompanyById($id)
{
$this->check('read'); //raise an exception if current user haven't READ privilege
parent::getCompanyById($id);
}
}
таким образом, вы не смешиваете обязанности и можете использовать полиморфизм
мои 2 цента
The Java EE model is pretty much on the lines of 2. Your code runs in a "Container", you tell the container about your interface entry points (URLs for servlets, methods for EJBs) and define the roles that can use these entry points. An adminstrator maps the authentication info (eg. LDAP user and groups) to specific roles and the container consults that mapping in granting access to the entry points.
The key here is that the Container "knows" about your code, it's effectively a quite clever proxy.
In the absence of a container I'd be looking at the proxy approach, perhaps using some kind of Aspect Oriented technique.
I think you're right that option 3 is very brittle,too much responsibility on the client programmers.