I was recently at a PHP conference in Odessa where I met many great developers. One of them asked me a question, that the answer was not obvious. His use case was that he wanted to use Symfonys Access Control configuration to restrict access in his application. But he also wanted to configure the rules dynamically.
Since all the configuration in Symfony is cached with the container for performance reasons, we could obviously not allow a use a database to somehow “print” new configuration. We need to do something smarter.
Using Symfony voters
Symfony is using voters to decide access to URL and resources. There are many
voters that come with the security component
that are using the configuration in
security.access_control to decide if the request
should be granted or not.
What we want to do is to create a new voter that access the database. How you create a Voter is covered by the Symfony documentation.
This class should be registered in the service container. If you are using
Symfony 4 with the standard
services.yaml it will be registered automatically.
If you need to register it manually, remember to add the
You also need to tell Symfony that you are using a access control:
MyDynamicAccessVoter will now be executed for every URL that starts with
“/admin”. You could of course change it to “/” to execute it on all requests.
Eventhough this solution is not obvious, it shows how powerful and flexible Symfony’s security component is.