在您的情况下,我将创建一个基本权限类,它将使用一种简单的方法涵盖特定限制消息的抽象,并将通过您的所有权限进行扩展。
这是抽象的权限蓝图。
abstract class AbstractPermission extends Permission
{
/**
* @return string
*/
abstract public function getRestrictionMessage(): string;
}
创建自定义数据库管理器以检查检索到的权限是否已实现抽象。
class CustomDbManager extends DbManager
{
/**
* @throws \Exception
* @return AbstractPermission|null
*/
public function getPermission($name): ?AbstractPermission
{
$permission = parent::getPermission($name);
if ($permission === null) {
return null;
}
if (!$permission instanceof AbstractPermission) {
throw new \Exception(
'Your permission class should be derived from ' . AbstractPermission::class
);
}
return $permission;
}
}
CustomDbManager
在你的配置文件中定义
'components' => [
'authManager' => [
'class' => CustomDbManager::class
],
...
];
以您的PostCommentPermission
.
class PostCommentPermission extends AbstractPermission
{
/**
* @return string
*/
public function getRestrictionMessage(): string
{
return 'You cannot post comments!';
}
}
最后通过特定权限检查调用您的经理
$authManager = Yii::$app->getAuthManager();
$postCommentPermission = $authManager->getPermission('postComment');
if (Yii::$app->user->can($postCommentPermission->name, ['comment' => $comment])) {
$comment->post();
} else {
throw new ForbiddenHttpException($postCommentPermission->getRestrictionMessage());
}