[英]How to load parameters with different values based on user role in Symfony?
I have a multitude of parameters in parameters.yml
file, each parameter should have a different value based on logged in user's role.我在parameters.yml
文件中有多个参数,每个参数都应根据登录用户的角色具有不同的值。
Is there is way to systematically decide and load correct value based on logged in user's role?有没有办法根据登录用户的角色系统地决定和加载正确的值?
Example:例子:
parameters:
user.address_code
manager.address_code
Ideally, I don't want to add conditions in my code for manager
or user
before I use address_code
.理想情况下,在使用address_code
之前,我不想在我的代码中为manager
或user
添加条件。
Since parameters values are used during the container compilation, their value cannot be changed at runtime .由于在容器编译期间使用参数值,因此它们的值不能在运行时更改。
And since the user role can only be known during a request, what you want to do simply cannot be done.而且由于用户角色只能在请求期间知道,因此您想要做的事情根本无法完成。
But you are most likely you are approaching the problem from the wrong end.但是您很可能是从错误的一端解决问题的。
Just encapsulate the logic in a service of some kind.只需将逻辑封装在某种服务中即可。 A simplistic example:一个简单的例子:
The service:服务:
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] ?? '';
}
}
Your parameters:您的参数:
# services.yaml
parameters:
address_code:
ROLE_USER: 'foo'
ROLE_ADMIN: 'bar'
Configuration to make sure the service know about your parameters:配置以确保服务了解您的参数:
#services.yaml
App\Service\FooService:
arguments: ['%address_code%']
Then it's only a matter of injecting FooService
wherever you need these values, and call getAddressCodeFor($role)
where you need it:然后只需在需要这些值的地方注入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]);
}
}
This is just an example, but you can adjust it to follow your needs.这只是一个示例,但您可以对其进行调整以满足您的需要。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.