Goals
● Understanding what
dependency injection is, and a
few patterns to achieve it.
● You know how CakePHP does
dependency injection internally.
● You know what is coming next.
… is a technique in which an object receives other
objects that it depends on. These other objects are
called dependencies. In the typical "using"
relationship the receiving object is called a client and
the passed (that is, "injected") object is called a
service.
-Wikipedia
Application Services
Contain one or more of:
● Logic that combines and coordinates multiple models.
● Logic that combines models with remote API.
● Logic that combines several remote APIs together.
● Logic that combines remote APIs and email.
● Logic that combines other services together.
● Or a variety of other things.
Registering Services
public function register(
ContainerInterface $container
): ContainerInterface
{
$container->add(...);
$container->add(...);
return $container;
}
Bundling Services
class BillingServiceProvider extends AbstractServiceProvider
{
// A list of services provided
protected $provides = [
‘AppServiceInvoiceService’,
];
public function register()
{
$this->getContainer()->add(...);
}
}
// Add a service provider
$container->addServiceProvider(BillingServiceProvider::class);
Handling Configuration
use CakeCoreServiceConfig;
// Add a read-only wrapper around Configure.
$container->share(ServiceConfig::class);
// Add scalar values you can reference by name in
definitions.
$container->add(‘apiKey’, ‘abc123’);
Getting Services
If defined in the container, CakePHP will inject services into:
● Controller constructors
● Command constructors
Automatically based on reflection into:
● Controller actions
Controller Actions
// Parameters to controllers
public function upgrade(BillingService $billing) { … }
// Parameters to controllers with routing parameters
public function modify($id, BillingService $billing) { … }