[英]How to load parameters with different values based on user role in Symfony?
我在parameters.yml
文件中有多個參數,每個參數都應根據登錄用戶的角色具有不同的值。
有沒有辦法根據登錄用戶的角色系統地決定和加載正確的值?
例子:
parameters:
user.address_code
manager.address_code
理想情況下,在使用address_code
之前,我不想在我的代碼中為manager
或user
添加條件。
由於在容器編譯期間使用參數值,因此它們的值不能在運行時更改。
而且由於用戶角色只能在請求期間知道,因此您想要做的事情根本無法完成。
但是您很可能是從錯誤的一端解決問題的。
只需將邏輯封裝在某種服務中即可。 一個簡單的例子:
服務:
namespace App\Service;
class FooService
{
private array $configuration;
public function __construct(array $configuration)
{
$this->configuration = $configuration;
}
public function getAddressCodeFor(string $role): string
{
return $this->configuration[$role] ?? '';
}
}
您的參數:
# services.yaml
parameters:
address_code:
ROLE_USER: 'foo'
ROLE_ADMIN: 'bar'
配置以確保服務了解您的參數:
#services.yaml
App\Service\FooService:
arguments: ['%address_code%']
然后只需在需要這些值的地方注入FooService
,並在需要的地方調用getAddressCodeFor($role)
:
class FakeController extends AbstractController
{
private FooService $paramService;
public function __construct(FooService $service)
{
$this->paramService = $service;
}
public function someAction(): Response
{
$address_code = $this->paramService->getAddressCodeFor('ROLE_ADMIN');
return $this->json(['address_code' => $address_code]);
}
}
這只是一個示例,但您可以對其進行調整以滿足您的需要。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.