layer without compromising all the other parts of the application • We need to use different implementations in different deployments (dragon game, monster game, etc…) • We wish to deploy the application in different environments (testing, integration, staging, production, etc…) • We need different configurations in each environment
but each deployment has specific infrastructure needs • Multiple environments with different needs • We want to automatically test all the things • We want to go fast, and the only way to go fast is… you know…
bad, but it also suggest that coupling is unavoidable • An absolutely decoupled application is useless because it adds no value • Developers can only add value by coupling things together
other components do, but rely on their contracts • Use an interface to define a type and focus on what is important • Concrete implementations of the interfaces should be be instantiated outside the component
is immutable • The constructor is only ever called once when the object is created, so you can be sure that the dependency will not change during the object's lifetime Pros Cons • It is not suitable for working with optional dependencies • Difficult to use in combination with class hierarchies
If dealing with legacy code that does not support it, consider using an adapter class with constructor injection • Depends on abstractions (interfaces), not concrete implementations TIPS
• The “injector” has to call the method in order to inject the dependency ! class LoggerChain implements SQLLogger! {! private $loggers = array();! ! public function setLogger(SQLLogger $logger)! {! $this->logger = $logger;! }! }!
you do not need the dependency, then just do not call the setter • You can call the setter multiple times. This is particularly useful if the method adds the dependency to a collection Pros Cons • Works “well” with optional dependencies Are you sure you need optional dependencies? • You can call the setter multiple times • You are not sure if the dependency was set
dependencies is not inmutable) • If you do Dependency Inversion right, probably YANGI • Remember, your classes depend on abstractions, not concrete implementations, so you can use Null or Dummy implementations when necessary
private $logger;! ! function __construct(. . ., LoggerInterface $logger)! {! $this->logger = $logger;! }! }! ! final class GoodManLogger implements LoggerInterface {…}! ! final class LogstarLogger implements LoggerInterface {…}! ! final class NullLogger implements LoggerInterface {…}! Instead of having a setter method to inject the logger, use constructor injection and use the appropriate logger implementation in each case
• Allows certain objects to be injected into other objects, that implement a common interface • It’s a kind of setter injection, so same pros and cons interface ContainerAwareInterface! {! public function setContainer(ContainerInterface $container = null);! }! ! class ContainerAwareEventDispatcher implements ContainerAwareInterface! {! public function setContainer(ContainerInterface $container = null)! {! }! }!
directly • There are mainly only disadvantages to using property injection, it is similar to setter injection but with additional important problems ! ! class NewsletterManager! {! public $mailer;! ! // ...! }!
that is out of your control, such as in a 3rd party library, which uses public properties for its dependencies Pros Cons • You cannot control when the dependency is set at all, it can be changed at any point in the object's lifetime • You cannot use type hinting so you cannot be sure what dependency is injected except by writing into the class code to explicitly test the class instance before using it
get all of the services that an another service might need interface CommandHandlerLocator ! {! public function locate($commandName);! }! ! ! class ContainerCommandHandlerLocator implements CommandHandlerLocator! {! private $container;! ! public function __construct(ContainerInterface $container)! {! $this->container = $container;! }! ! public function locate($commandName)! {! if (!$this->container->has($commandName)) {! throw new NotFoundException('Unable to find command handler');! }! ! return $this->container->get($commandName);! }! }!
to its straightforward behaviour • Not all use cases are bad, for example when you want to load services on demand at runtime Pros Cons • It hides dependencies in your code making them difficult to figure out and potentially leads to errors that only manifest themselves at runtime • It becomes unclear what are the dependencies of a given class • It’s easy to abuse • It’s consider and anti-pattern (but there are valid use cases for it)
a DIC to benefit from Dependency Injection • But… creating and maintaining the dependencies by hand can become a nightmare pretty fast • A DIC manages objects from their instantiation to their configuration • The objects themselves should not know that they are managed by a container and should not know nothing about it
should be constructed (XML, YAML, PHP, etc…) • Collects all definitions and builds a container • When requested, creates objects and injects the dependencies
in the Symfony official documentation • Probably you are comfortable creating your own objects via the container • So, let’s try to solve the problems we stated at the beginning
what concrete implementation a deployment or environment is going to use • We must configure dependencies for all the concrete implementations and each one has their own dependencies
kernel.environment • Probably easy to setup for testing/dummy services Pros Cons • The choice is coupled to the environment • All services get defined, even when you are not going to use them
services • Probably easy to setup for testing/dummy services Pros Cons • All services get defined, even when you are not going to use them • You have to define dependencies of services you probably not are going to use
the user override individual parameters, you let the user configure just a few, specifically created options. • As the bundle developer, you then parse through that configuration and load services inside an “Extension" • With this method, you won't need to import any configuration resources from your main application configuration: the Extension class can handle all of this
you are building a bundle to be used by 3rd parties and you have a lot of configuration options you want to validate • Lot of boilerplate code • Extra complexity added • You just wanted to manage dependency injection right?
simply defining parameters: a specific option value might trigger the creation of many service definitions; • Ability to have configuration hierarchy • Smart merging of several config files (e.g. config_dev.yml and config.yml) Pros Cons • Too much verbose, a lot of boilerplate code • Extra complexity added if you only want to define dependencies and not a long configuration tree !
Component Exports Depends On Unit Of Work Storage Driver Order Processor Product Repository Order Repository Payment Gateway Tracker Tracker Queue Implementations Redis, Zookeper Redis, C*, Riak, MySql Config, API MySql, C* Itunes, Facebook, Amazon, Google Play Redis, RabbitMQ, SQS, Kinesis
Unit Of Work Storage Driver Implementations Redis, Zookeper Redis, C*, Riak, MySql namespace SP\Core\Game\Framework;! ! class FrameworkComponent implements Component! {! public function getName()! {! return 'core.game.framework';! }! ! public function getServicesDefinition()! {! return ServicesDefinition::create()! ! ->dependsOn('storage_driver')! ->withInstanceOf('SP\Core\Component\ObjectStore\Storage\StorageDriver')! ! ->dependsOn('lock_system')! ->withInstanceOf('SP\Core\Component\Lock\LockSystem')! ! ->exports('object_store')! ->withClass('SP\Core\Component\ObjectStore')! ->andConstructorDependencies(‘storage_driver’, ‘lock_system’);! }! } These are the decisions the component developer wants to defer Depends on abstractions, not concrete implementations
MySql, C* namespace SP\Core\Game\Payment;! ! class PaymentComponent implements Component! {! public function getName()! {! return 'core.game.payment';! }! ! public function getServicesDefinition()! {! return ServicesDefinition::create()! ! ! ! ! ->dependsOn('product_repository')! ->withInstanceOf('SP\Core\Game\Payment\Product\Repository\ProductRepository')! ! ->dependsOn('order_repository')! ->withInstanceOf('SP\Core\Game\Payment\Order\Repository\OrderRepository')! ! ->dependsOn('gateways')! ->withInstanceOf('GatewayDefinition')! ! ->exports(‘order_processor')! ->withClass('SP\Core\Game\Payment\OrderProcessor')! ->andConstructorDependencies(‘gateways', ‘product_repository’, ‘order_repository’);! }! } Itunes, Facebook, Amazon, Google Play Payment Gateway These are the decisions the component developer wants to defer Depends on abstractions, not concrete implementations
such “magic” • Each component define it’s dependencies in a easy and legible way • Framework agnostic dependency definition • Based on the dependency definitions, services are added to the container during the container building phase
public function registerBundles()! {! $bundles = array(! new Symfony\Bundle\FrameworkBundle\FrameworkBundle(),! new Symfony\Bundle\MonologBundle\MonologBundle(),! ! new SP\Core\Bundle\GameFrameworkBundle\GameFrameworkBundle([! new \SP\Core\Game\Framework\FrameworkComponent(),! new \SP\Core\Game\Framework\PaymentComponent(),! new \SP\Core\Game\Framework\AnalyticsComponent(),! ]),! );! }! }! The AppKernel These are the framework agnostic components that provide infrastructure and logic for the application
use SP\Core\Bridge\Symfony\DependencyInjection\ComponentDependencyInjector;! ! class GameFrameworkBundle extends Bundle! {! private $components;! ! function __construct(array $components = array())! {! $this->components = $components;! }! ! public function build(ContainerBuilder $container)! {! $injector = new ComponentDependencyInjector($this->components);! $injector->registerComponentsDependencies($container);! ! $container->addCompilerPass($injector, PassConfig::TYPE_BEFORE_REMOVING);! }! }! The (in)Famous Framework Bundle The components we are “installing” in this application The “magic” is here !!!
of "SP\Core\Component\Lock \LockSystem" but the service is not defined. [SP\Core\Bridge\Symfony\DependencyInjection\Exception\ServiceNotFoundException] Component "core.game.payment" requires the service “core.game.payment.product_repository” as an implementation of "ProductRepository" but the service is not defined. $ php app/console The application complains about missing dependencies required by installed components We are planning to add suggested implementations for this requirement
dependencies • Very limited in features (only constructor injections allowed) • Framework agnostic • Allows you to defer critical and volatile decisions Pros Cons • Very limited in features (only constructor injections allowed) ! !