I have a multitude of parameters in parameters.yml
file, each parameter should have a different value based on logged in user’s role.
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
.
Advertisement
Answer
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 AppService; 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 AppServiceFooService: 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:
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.