在类外验证可能更糟,因为存在授权检查错误或完全错过的真正危险。它还会在对象之间创建错误类型的链接,因为对象本身不受控制。
如果要在创建对象时在对象外部执行此操作,则最好要求对象提供
interface
例如可以由单独的对象验证的iaauthorisable。
例如
interface IAuthorisable
{
public function getRequirements();
}
class Authorisation
{
public static createObject($newObj)
{
if ( canDo( $newObj->getRequirements()) )
return $newObj;
return null;
}
}
class Something implements IAuthorisable
{
public function getRequirements()
{
return SomeSortOfIdentifierOrSomething;
}
}
$mySomething = Authorisation::createObject(new Something($p1, $p2), "
如果$mysomething为空,则不允许。显然,这需要适当地扩展和设计,这留给读者作为练习。