I'm using symfony/dependency-injection component (note: not using the full stack framework)
When registering a new service i want to inject in the constructor a new instance of a class. Example:
$container->register('session', 'Vendor\Core\Session')
->addArgument(new PhpBridgeSessionStorage());
The example works very well but what if I want to use yml files for defining this service? Something like:
services:
session:
class: Vendor\Core\Session
arguments: [ new Class\To\Inject ]
Am I forced to define Class\To\Inject as a new service? or create a Service factory?
This means that each time you retrieve the service, you'll get the same instance. This is usually the behavior you want, but in some cases, you might want to always get a new instance. In order to always get a new instance, set the shared setting to false in your service definition: YAML.
The Dependency Injection Container in Symfony2 allows components to be injected with their dependencies, and is often used as a Service Locator, which when combined with the DI-container pattern is considered to be an anti-pattern by many.
Dependency injection is a pattern to allow your application to inject objects on the fly to classes that need them, without forcing those classes to be responsible for those objects. It allows your code to be more loosely coupled, and Entity Framework Core plugs in to this same system of services.
Scopes have been deprecated since 2.8. Use shared: false
instead.
http://symfony.com/doc/current/cookbook/service_container/shared.html
services:
session:
class: Vendor\Core\Session
arguments: [ "@inject.me" ]
inject.me:
class: Class\To\Inject
shared: false
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With