In addition to the relative ordering of tagged services and decorators, Symfony 8.2 adds many other features to the DependencyInjection component. Some of them target applications and others are mostly useful for bundle authors.
Injecting Lazy Proxies per Argument
Marking a service as lazy affects all the services that use it. When only
one of them needs to defer its creation, you can apply the #[Lazy] attribute
to that argument, but YAML and PHP config had no equivalent.
Symfony 8.2 adds the @~ prefix and the !lazy_proxy tag in YAML, and the
lazy_proxy() function in PHP:
1 2 3 4 5 6 7
# config/services.yaml
services:
App\Report\MonthlyReportGenerator:
arguments:
- '@~App\Pdf\PdfRenderer'
# the tag is needed to create a proxy of some interface(s)
- !lazy_proxy { service: '@App\Storage\S3Storage', interface: 'App\Storage\StorageInterface' }
The other services that use PdfRenderer and S3Storage still get the real
objects. The @~ prefix can be combined with the existing ones (e.g.
@~?App\Pdf\PdfRenderer for an optional dependency).
Declaring Methods as Services
The from_callable option allows you to define a method of a service as a
service of its own. With attributes, you could only do that where the callable
is injected, using #[AutowireCallable], so those methods couldn't be
collected by tag like the rest of services.
Symfony 8.2 adds the #[AsCallable] attribute, which turns a public method
into a tagged service:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
// src/Report/TabularExporter.php
namespace App\Report;
use Symfony\Component\DependencyInjection\Attribute\AsCallable;
final class TabularExporter
{
#[AsCallable(tags: [['app.report_exporter' => ['format' => 'csv']]])]
public function exportCsv(Report $report): string
{
// ...
}
// other methods can define their own #[AsCallable] attribute
}
Each method becomes a private \Closure service (called
App\Report\TabularExporter::exportCsv by default), so
#[AutowireLocator('app.report_exporter', indexAttribute: 'format')] and
#[AutowireIterator] collect them together with the other services that have
the same tag.
These services are lazy by default: TabularExporter is not instantiated
until one of the closures is called. If you prefer objects to closures, pass a
single-method interface to the lazy option (e.g.
#[AsCallable(lazy: ReportExporterInterface::class, ...)]) and Symfony
generates a service that implements it.
Computing Tag Attributes per Class
Symfony 8.1 deprecated the default index and priority methods of tagged iterators and locators. Those methods had one nice property: declaring them in an interface made the keys of a locator checkable by static analysis tools.
Symfony 8.2 brings that back on the tagging side. The attributes of a tag can now be computed for each tagged class, instead of being the same array for all of them:
1 2 3 4 5 6 7 8 9 10 11 12
// src/Payment/PaymentHandlerInterface.php
namespace App\Payment;
use Symfony\Component\DependencyInjection\Attribute\AutoconfigureTag;
#[AutoconfigureTag('app.payment_handler', attributes: static function (string $class): array {
return ['key' => $class::getProvider()];
})]
interface PaymentHandlerInterface
{
public static function getProvider(): string;
}
Closures in attributes require PHP 8.5. In PHP 8.4, pass a
[class-string, method] callable. The static method is called on each tagged
class:
1 2 3 4 5
#[AutoconfigureTag('app.payment_handler', attributes: [self::class, 'getTagAttributes'])]
interface PaymentHandlerInterface
{
public static function getTagAttributes(): array;
}
Then, use #[AutowireLocator('app.payment_handler', indexAttribute: 'key')]
to get a locator indexed by those values. The callable form also works in the _instanceof section of YAML files
(- app.payment_handler: [App\Payment\PaymentHandlerInterface, getTagAttributes]).
Both forms work in #[Autoconfigure] too, and in resource tags via
#[AutoconfigureResourceTag].
Injecting Class Maps
Resource tags are attached to classes instead of services, which makes them useful for classes that the container never instantiates (messages, DTOs, value objects, etc.). However, using them required writing a compiler pass.
Symfony 8.2 adds the #[AutowireClassMap] attribute to inject an array that
maps an index to the name of each tagged class:
1 2 3 4 5 6 7 8 9 10
// src/Webhook/Event/InvoicePaid.php
namespace App\Webhook\Event;
use Symfony\Component\DependencyInjection\Attribute\AutoconfigureResourceTag;
#[AutoconfigureResourceTag('app.webhook_event', ['type' => 'invoice.paid'])]
final class InvoicePaid
{
// ...
}
1 2 3 4 5 6 7 8 9 10 11 12 13
// src/Webhook/EventFactory.php
namespace App\Webhook;
use Symfony\Component\DependencyInjection\Attribute\AutowireClassMap;
final class EventFactory
{
public function __construct(
#[AutowireClassMap('app.webhook_event', indexAttribute: 'type')]
private array $eventClasses, // ['invoice.paid' => InvoicePaid::class, ...]
) {
}
}
Tagged classes are not registered as services and the map only contains
concrete classes. Combined with the computed attributes of the previous section,
you can tag an interface once and take the index from a static method of each
class. In config files, use the !tagged_class_map YAML tag and the tagged_class_map()
PHP function.
Factories in Autoconfiguration
The #[Autoconfigure] attribute allows you to define most of the service
options next to the class, but not its factory. In Symfony 8.2, the attribute
has a new factory argument, which accepts the same values as the factory
option of service definitions:
1 2 3 4 5 6 7 8 9 10
// src/Api/InvoicingClient.php
namespace App\Api;
use Symfony\Component\DependencyInjection\Attribute\Autoconfigure;
#[Autoconfigure(factory: ['@App\Api\ClientFactory', 'createInvoicingClient'])]
final class InvoicingClient
{
// ...
}
Other valid values are '@App\Api\InvokableFactory',
[StaticFactory::class, 'create'], [null, 'create'] (a static method of
the class itself) and expressions such as
'@=service("App.
The factory key is now also allowed in _instanceof conditionals, both in
YAML and in the array-based PHP config format.
Resolving Env Vars at Compile Time
When a bundle option is set to an env var (e.g. '%env(bool:AUDIT_LOG)%'),
the bundle extension gets a placeholder string instead of the real value. That's
a problem for the options that decide which services to register, because the
placeholder is always truthy.
In Symfony 8.2, a config node can declare that it needs the real value while the container is compiled:
1 2 3 4 5 6 7
// src/DependencyInjection/Configuration.php
$rootNode
->children()
->booleanNode('audit_log')->resolvesAtCompileTime()->defaultFalse()->end()
->arrayNode('regions')->resolvesAtCompileTime()->scalarPrototype()->end()->end()
->end()
;
The env vars of those nodes are resolved before loading the extension, so
$config['audit_log'] is a real boolean. The values are inlined in the
compiled container: if the env var changes, you must rebuild the container. The
debug:container --env-vars command shows a new "Inlined" column to tell
which env vars are used like this.
Note
The enabled option created by canBeEnabled() and canBeDisabled()
now uses this feature, as well as other Symfony options used to build the
container. A config like enabled: '%env(bool:FOO)%' used to enable the
section whatever the value of FOO. Now the section is disabled when
FOO is false and the container fails to compile when FOO is not
defined at that point.
Ignoring Classes When Preloading
The preloading file generated by Symfony follows the types of the properties, arguments and return values of your services. If a service uses a large SDK, thousands of classes can end up preloaded for no benefit.
Symfony 8.2 adds the Preloader::ignore() method to exclude a class, or a
whole namespace when the name ends with a backslash:
1 2 3 4 5 6 7 8 9 10 11
// config/preload.php
use Symfony\Component\DependencyInjection\Dumper\Preloader;
require_once dirname(__DIR__).'/vendor/autoload.php';
Preloader::ignore('Microsoft\\Graph\\');
Preloader::ignore(App\Legacy\CountryRegistry::class);
if (file_exists(dirname(__DIR__).'/var/cache/prod/App_KernelProdContainer.preload.php')) {
require dirname(__DIR__).'/var/cache/prod/App_KernelProdContainer.preload.php';
}
Deprecated Autowiring Aliases of Implementations
Some Symfony services were autowirable by their concrete class. For example,
each webhook request parser of the Mailer and Notifier bridges had its own
alias. Symfony 8.2 deprecates those aliases. Type-hint the interface instead and
select the implementation with the #[Target] attribute:
1 2 3 4 5 6 7 8 9
-use Symfony\Component\Mailer\Bridge\Mailgun\Webhook\MailgunRequestParser;
+use Symfony\Component\DependencyInjection\Attribute\Target;
+use Symfony\Component\Webhook\Client\RequestParserInterface;
public function __construct(
- private MailgunRequestParser $parser,
+ #[Target('mailer.mailgun')] private RequestParserInterface $parser,
) {
}
Targets are prefixed with mailer. or notifier. (e.g.
notifier.twilio). The other deprecated aliases are:
JsonStreamWriterandJsonStreamReader: useStreamWriterInterfaceandStreamReaderInterface;- the generic
RequestParserof the Webhook component: use#[Target('webhook')]withRequestParserInterface, and thewebhook.request_parserservice ID in theserviceoption of webhook routes; - the
Firewallclass of the Security component, which has no replacement because it's an event listener not meant to be injected.
The deprecated aliases will be removed in Symfony 9.0.
Releasing Resources on Shutdown
Services that implement ResetInterface are reset between requests and
messages, and they must remain usable after that. This means that reset()
can't close connections or release other resources that are only safe to drop
when the application ends.
Symfony 8.2 adds a ShutdownInterface to the service contracts. It extends
ResetInterface and its reset() method receives a flag, which is true
when the kernel shuts down:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
// src/Exchange/RateProvider.php
namespace App\Exchange;
use Symfony\Contracts\Service\ShutdownInterface;
final class RateProvider implements ShutdownInterface
{
private array $rates = [];
private ?Connection $connection = null;
// ...
public function reset(bool $shutdown = false): void
{
$this->rates = [];
if ($shutdown) {
// the service won't be used again
$this->connection?->close();
$this->connection = null;
}
}
}
Autoconfiguration takes care of everything. If you tag services yourself, the
kernel.reset tag has a new on_shutdown attribute: set it to flag to
pass the flag to the method, or to only to call the method only on shutdown
(e.g. { name: kernel.reset, method: disconnect, on_shutdown: only }).
Removing Services with Missing Dependencies
Bundles often register services that only make sense when some other service, class or package is available (e.g. a data collector is useless without the profiler). Removing them required a compiler pass that repeated, far from the definition, what each service needs.
Symfony 8.2 adds the container.remove_if_missing tag, so the definition
itself declares its requirements:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
// config/services.php
use Symfony\Component\Workflow\Workflow;
$services
->set('acme_billing.data_collector', BillingDataCollector::class)
->tag('data_collector', ['id' => 'acme_billing'])
->tag('container.remove_if_missing', ['service' => 'profiler'])
->set('acme_billing.workflow_listener', InvoiceWorkflowListener::class)
->tag('kernel.event_subscriber')
->tag('container.remove_if_missing', [
'package' => 'symfony/workflow',
'class' => Workflow::class,
])
;
Each tag defines a condition based on a service, a class, or a class
of a given package. All the tags of a definition must be met. The only
exception is a list of services (['service' => ['profiler', 'test.client']]),
which is met when any of them exists.
Removals cascade (a service that requires a removed service is removed too),
aliases are removed with their services, and each removal is added to the
compiler log with its reason. Older versions of the container ignore this tag,
so bundles that use it must require symfony/dependency-injection 8.2 or
higher.