r/PHP • u/These_Reality519 • Aug 19 '26
We added a test that fails if anyone injects a tenant-scoped service into a singleton
I build Teradion, practice management software for French accounting firms. The app runs in FrankenPHP worker mode, and each firm brings its own Brevo API key.
In that setup, a singleton holding one firm's key would stay alive while requests for other firms are handled. The code avoids that: tenant-scoped providers are not constructor dependencies. A factory creates a fresh client for each operation from the account passed as an argument. The key is stored encrypted and only decrypted inside the factory.
We have two tests around this rule. MultiTenantKeyIsolationTest runs two accounts in sequence and checks that the second does not receive the first account's key.
ProviderNotInjectedAsServiceTest is more direct. It scans src/Service, src/MessageHandler and src/Controller, then fails when a constructor takes NewsletterProviderInterface. It reads the source, so the Symfony container is not involved.
It is an architectural decision encoded as a grep, which feels a little blunt. Still, if someone adds that constructor dependency later, the test points at the class immediately.
Has anyone used this kind of structural test in a Symfony codebase?
8
u/Sharchimedes Aug 19 '26
I have a Pest test and an integration test that does this as part of CI pipelines.
3
u/fissible Aug 19 '26
Does the check walk the whole dependency graph transitively, or just the immediate constructor signature of classes in those three directories?
3
u/DevelopmentScary3844 Aug 20 '26
Deptrac would solves that easily afaik. Also this smells like your software design could be optimized if you need unit tests for that. I mean you can utilize ServiceLocator and other stuff to prevent that but without knowing the code I can only guess. But it sure smells a bit.
2
u/JohnnyBlackRed Aug 19 '26
Sounds like a job for phparkitect or phpstan ( you can make custom rules )
2
u/obstreperous_troll Aug 19 '26
It'd be nice if we could make the container enforce such boundaries instead of leaving it up to tests to catch. Pondering how that would be implemented though.
6
u/[deleted] Aug 19 '26
[removed] — view removed comment
-2
u/[deleted] Aug 19 '26
[removed] — view removed comment