[英]How to allow the user ROLE_USER access to the SonataAdminBundle service?
[英]How to allow access to PHP methods according to user's role?
我有一個基本的用戶模型,可以滿足一般用戶的所有需求。 我現在需要為用戶創建幾個不同的角色,每個角色具有大約10-20種不同的方法,而其他角色則無法使用。
假設我必須加載通用User類來確定用戶的角色...
由於將這么多不同的基於角色的方法打包到通用User模型中效率低下且繁瑣(當所有角色無法使用它們時),最好的方法是讓用戶僅在他們使用基於角色的方法時訪問它們需要他們嗎?
這是我要提出的一些想法:
每個角色都有一個單獨的服務類,並根據用戶的角色將其提供給User類
只需在用戶類中查找所有方法,然后僅在用戶具有正確角色時才允許訪問每個方法。
完全重構並使基於角色的類繼承自User類。
這些好主意中有什么,還是有更好的主意?
為什么不將基於角色的類組合到User對象中呢?
$user = new User(/* pass role as an arg */);
// Internally:
// if ($user->getRole() instanceof AdminRole) or similar...
if ($user->isAdmin()) {
// AdminRole::doSomethingAdminish()
$user->getRole()->doSomethingAdminish();
}
看一下工廠模式。 從本質上講,您向其傳遞了實例化對象所需的數據,並且它以就緒狀態返回正確的對象。
也許像
class UserFactory
{
public static function getUser($userId)
{
$user = new User($userId);
switch ($user->getType()) {
case 'admin' :
return new AdminUser($user);
case 'guest' :
return new GuestUser($user);
default :
//handle
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.