Dependency injection in CakePHP 5: services, providers and testing
How the CakePHP 5 service container works: where CakePHP injects services, when a service is worth it, shared services, configuration injection, service providers, the optional 5.4 built-in container, and swapping services in tests.
Updated 8 min read

In this article
Part 7 of 10
CakePHP 5 from upgrade to production
All partsHide
Part 7 of 10
CakePHP 5 from upgrade to production
Getting onto the current version, building an API and its security, then performance, tests and release.
Dependency injection in CakePHP 5: services, providers and testing
You are here · 8 min read
Controllers in older CakePHP applications tend to grow. They load tables, call external APIs, send email, write files and log, all in the same action. That code works, but it is hard to test without sending real email or calling a real payment gateway, and hard to reuse from a console command or a queue job.
Dependency injection in CakePHP 5 is built on a PSR-11 service container. You define services in Application::services(), group related definitions in a service provider, inject them into controllers, commands and components, and swap them for fakes in tests.
CakePHP 5 includes a PSR-11 service container that fixes this without a separate framework. You define services in Application::services(), and CakePHP injects them into controller constructors, controller actions, components, commands and middleware. This article explains how the container works in CakePHP 5.4, when it is worth using, how to organise services with providers, and how to replace services with fakes in tests.
Everything here follows the Dependency Injection chapter of the CakePHP 5.x book, checked on 7 October 2026.
Dependency injection in CakePHP 5: where the container is used
The container is not only for your own services. According to the book, CakePHP uses it when:
- constructing controllers;
- calling controller actions (so actions can take service parameters);
- constructing components;
- constructing console commands;
- constructing middleware added by class name.
Your services can also depend on the current ServerRequest in controller actions, because CakePHP adds it to the container automatically.

When a service is worth it, and when it is not
The book is direct about this: dependency injection is not always necessary. Simple CRUD belongs in table classes used from controllers; entity-specific logic belongs on entities; formatting belongs in helpers; validation belongs in table validation rules. Reach for a service when you have:
- a business workflow spanning several models (placing an order, onboarding a customer);
- an external API integration (payments, email providers, storage);
- logic reused by several controllers, commands or jobs;
- code that needs extensive unit testing in isolation.
A useful rule: if you would have to mock something to test the controller action, that something probably belongs in a service.
Defining and injecting a service
Start with a plain class. Here an invoice service depends on an interface for a payment gateway, so that the real gateway can be swapped for a fake:
<?php
declare(strict_types=1);
namespace App\Service;
interface PaymentGatewayInterface
{
public function charge(int $amountInCents, string $currency, string $reference): string;
}<?php
declare(strict_types=1);
namespace App\Service;
use App\Model\Table\InvoicesTable;
class InvoiceService
{
public function __construct(
private PaymentGatewayInterface $gateway,
private InvoicesTable $invoices,
) {
}
public function pay(int $invoiceId): void
{
$invoice = $this->invoices->get($invoiceId);
$chargeId = $this->gateway->charge($invoice->total_cents, $invoice->currency, 'INV-' . $invoice->id);
$invoice->charge_id = $chargeId;
$invoice->status = 'paid';
$this->invoices->saveOrFail($invoice);
}
}Register both in src/Application.php. The skeleton already contains an empty services() method with a commented-out line for table injection:
use App\Service\InvoiceService;
use App\Service\PaymentGatewayInterface;
use App\Service\StripePaymentGateway;
use Cake\Core\ContainerInterface;
use Cake\ORM\Locator\TableContainer;
public function services(ContainerInterface $container): void
{
// Let the container resolve ORM table classes (added in 5.3).
$container->delegate(new TableContainer());
$container->add(PaymentGatewayInterface::class, StripePaymentGateway::class);
$container->add(InvoiceService::class)
->addArgument(PaymentGatewayInterface::class)
->addArgument(\App\Model\Table\InvoicesTable::class);
}Now any controller action can ask for it by type:
// src/Controller/InvoicesController.php
public function pay(InvoiceService $invoices, string $id)
{
$this->request->allowMethod(['post']);
$invoices->pay((int)$id);
$this->Flash->success('Payment received.');
return $this->redirect(['action' => 'view', $id]);
}The service is created by the container on demand. Route parameters such as $id are still passed to the action as before.
Shared or not?
Services are not shared by default: every fetch creates a new instance along with its dependencies. Use addShared() when one instance should be reused, for example an API client that holds a connection pool or a configuration object:
$container->addShared(StripePaymentGateway::class);Configuration values
Never hard-code keys in service definitions. Since CakePHP 5.3 you can inject a single configuration value with the #[Configure] attribute, or inject a read-only ServiceConfig object that exposes all configuration:
use Cake\Core\Attribute\Configure;
class StripePaymentGateway implements PaymentGatewayInterface
{
public function __construct(
#[Configure('Stripe.secretKey')] private string $secretKey,
) {
}
// charge() implementation ...
}Keep the actual secret in an environment variable that config/app_local.php reads, so it never lands in version control.
Constructor injection in commands and components
Commands and components are built by the container too, but you define them as services with their arguments. For a command, the book's pattern is to add the command itself and pass the service plus the command factory:
// src/Command/ChargeOverdueCommand.php
use Cake\Command\Command;
use Cake\Console\Arguments;
use Cake\Console\CommandFactoryInterface;
use Cake\Console\ConsoleIo;
class ChargeOverdueCommand extends Command
{
public function __construct(
protected InvoiceService $invoices,
?CommandFactoryInterface $factory = null,
) {
parent::__construct($factory);
}
public function execute(Arguments $args, ConsoleIo $io): int
{
// ... find overdue invoices and call $this->invoices->pay($id)
return static::CODE_SUCCESS;
}
}
// src/Application.php, inside services()
$container->add(ChargeOverdueCommand::class)
->addArgument(InvoiceService::class)
->addArgument(CommandFactoryInterface::class);Now the same payment logic runs from the web and from cron without duplication. Components follow the same shape: the constructor takes the ComponentRegistry, your services, and the config array, and you register the component with matching arguments.

Organising services with providers
As an application grows, services() becomes long. Service providers group related definitions, and they are registered lazily: their services are only defined when one of them is first requested. Every service a provider offers must be listed in $provides, or it cannot be loaded from the container.
<?php
declare(strict_types=1);
namespace App\ServiceProvider;
use App\Service\InvoiceService;
use App\Service\PaymentGatewayInterface;
use App\Service\StripePaymentGateway;
use Cake\Core\ContainerInterface;
use Cake\Core\ServiceProvider;
class BillingServiceProvider extends ServiceProvider
{
protected array $provides = [
PaymentGatewayInterface::class,
InvoiceService::class,
];
public function services(ContainerInterface $container): void
{
$container->addShared(PaymentGatewayInterface::class, StripePaymentGateway::class);
$container->add(InvoiceService::class)
->addArgument(PaymentGatewayInterface::class)
->addArgument(\App\Model\Table\InvoicesTable::class);
}
}
// src/Application.php, inside services()
$container->addServiceProvider(new BillingServiceProvider());A provider can also implement bootstrap() to load extra configuration or register further providers when it is added.
Auto-wiring: league/container or the new built-in container
CakePHP 5 uses league/container by default, and with it auto-wiring is off: the container only builds what you defined. You can turn auto-wiring on by delegating to a ReflectionContainer; pass true to cache resolutions, because uncached reflection costs performance.
CakePHP 5.4 adds an alternative: its own PSR-11 container in Cake\Container, enabled by setting App.container to cake in config/app.php. It auto-wires concrete classes and caches those resolutions by default, so in the example above only the interface mapping would be required. Your services() method keeps type-hinting Cake\Core\ContainerInterface, and add(), addShared(), extend(), tags and delegates work with both. Do not add a ReflectionContainer when using the built-in one.
| Question | league/container (default) | Built-in container (5.4, opt-in) |
|---|---|---|
| How to enable | Nothing to do | 'App' => ['container' => 'cake'] |
| Auto-wiring | Off unless you delegate to ReflectionContainer | On, with cached resolutions |
| Explicit definitions still needed for | Every service | Interfaces, scalars, arrays, shared services, custom arguments |
Service providers, tags, extend() | Yes | Yes |
Explicit definitions remain good practice for anything security-sensitive or expensive, because they document intent and control sharing.
Replacing services in tests
This is where the design pays off. In tests that use IntegrationTestTrait or ConsoleIntegrationTestTrait, mockService() swaps a container entry for the duration of the test; mocks are cleaned up automatically afterwards.
<?php
declare(strict_types=1);
namespace App\Test\TestCase\Controller;
use App\Service\PaymentGatewayInterface;
use Cake\TestSuite\IntegrationTestTrait;
use Cake\TestSuite\TestCase;
class InvoicesControllerTest extends TestCase
{
use IntegrationTestTrait;
protected array $fixtures = ['app.Invoices'];
public function testPayUsesGateway(): void
{
$this->mockService(PaymentGatewayInterface::class, function () {
return new class implements PaymentGatewayInterface {
public function charge(int $amountInCents, string $currency, string $reference): string
{
return 'test_charge_1';
}
};
});
$this->enableCsrfToken();
$this->post('/invoices/pay/1');
$this->assertRedirect(['action' => 'view', '1']);
}
}No network call is made, and the test asserts the behaviour you care about. CakePHP 5.4 also adds TestCase::mockModel() for Mockery-based model mocks when you need them.
Common mistakes to avoid
- Using the container as a service locator. Fetching services from the container inside business code hides dependencies again. Ask for them in constructors or action parameters instead, so the signature tells readers and tests what a class needs.
- Forgetting
$provides. A service defined in a provider but missing from its$providesarray cannot be loaded, and the resulting error can look like a missing definition. - Sharing stateful services by accident.
addShared()is right for stateless clients and configuration, but a shared object that stores per-request data can leak state between operations in long-running workers. - Turning every table call into a service. The book explicitly recommends using table classes directly for simple CRUD. A service that only forwards to
find()andsave()adds indirection without benefit. - Uncached auto-wiring in production. If you enable
ReflectionContainerwith the default league/container setup, passtrueso resolutions are cached; the book warns that uncached reflection can hurt performance. - Secrets in definitions. Keys passed as literal strings to
add()end up in version control. Read them from configuration that comes from the environment.
A sensible migration path for an existing application is incremental. Pick one controller action that talks to an external system, extract that code into a service with an interface, register it, inject it into the action, and write one integration test that mocks it. Repeat for the next integration. Within a few iterations the controllers become thin and the riskiest code is covered by fast tests.
Summary
Use the CakePHP container for workflows, integrations and logic shared across entry points, and leave plain CRUD in tables and controllers. Depend on interfaces for anything external, register services in services() or in lazily loaded providers, inject configuration with #[Configure], and swap implementations in tests with mockService(). If you are on 5.4, try the built-in container on a branch: it removes most boilerplate definitions while keeping the same API.
Frequently asked questions
Where can CakePHP inject services?
Into controller constructors and actions, components, console commands, and middleware that is added by class name, according to the CakePHP 5 book.
Are CakePHP container services singletons?
No. Services are not shared by default; each fetch builds a new instance. Use
addShared()for a single reused instance.Can I inject ORM tables into services?
Yes. Since CakePHP 5.3, delegate to
Cake\ORM\Locator\TableContainerinservices()and table classes can be resolved by the container.Does CakePHP auto-wire dependencies?
Not with the default league/container setup unless you delegate to a
ReflectionContainer. The built-in container added in 5.4, enabled withApp.containerset tocake, auto-wires concrete classes by default.
Sources
- Dependency Injection — CakePHP Book (5.x)
- 5.4 Migration Guide — CakePHP Book (5.x)
- 5.3 Migration Guide — CakePHP Book (5.x)
- cakephp/app skeleton Application.php (5.x branch) — CakePHP on GitHub
Part 8 of 10: CakePHP 5 from upgrade to production
Next part
Previous part
Resource guideCakePHP7 min read
Speed up the CakePHP 5 ORM: fix N+1 queries and heavy finds
Find and fix slow CakePHP 5.4 ORM queries: N+1 loops, contain() column bloat, matching(), the new subquery strategy, unhydratedFind(), CounterCache and caching.
Comments
No comments yet. Be the first to join the conversation.
Leave a comment
Every comment is read by a moderator before it appears. Your email address is never published; it is used only to contact you about this comment.
More from Cloudsoft Zone

TutorialDevOps5 min read
Deployment approval gates: when a production release needs a human decision
Use deployment approval gates for concrete production decisions with artifact identity, migration risk, acceptance evidence and a clear recovery plan before credentials are released.
By Nilesh Kushvaha

TutorialDevOps5 min read
CI/CD secrets: protect production credentials without exposing them to builds or logs
Manage CI/CD secrets with separate verification and deployment authority, short-lived identity where supported, narrow provider permissions and explicit exposure recovery.
By Nilesh Kushvaha

Industry updateDevelopment3 min read
GitHub Copilot model removals on 16 November: what to do
GitHub Copilot removes Claude Opus 4.8, Claude Opus 5 and GPT-5.6 Terra on 16 November 2026. See the replacements, the exception and the admin checks.
By Nilesh Kushvaha

TutorialDevOps5 min read
Automated rollback for VPS deployments: release identity, compatibility and recovery gates
Design automated rollback around an exact previous release, schema compatibility and verified user recovery instead of blindly reverting every failed deployment.
By Nilesh Kushvaha
