CakeDC Blog

TIPS, INSIGHTS AND THE LATEST FROM THE EXPERTS BEHIND CAKEPHP

Clean DI in CakePHP 5.3: Say Goodbye to fetchTable()

This article is part of the CakeDC Advent Calendar 2025 (December 23rd, 2025)

Introduction: The Death of the "Hidden" Dependency

For years, accessing data in CakePHP meant "grabbing" it from the global state. Whether using TableRegistry::getTableLocator()->get() or the LocatorAwareTrait’s $this->fetchTable(), your classes reached out to a locator to find what they needed.

While convenient, this created hidden dependencies. A class constructor might look empty, despite the class being secretly reliant on multiple database tables. This made unit testing cumbersome, forcing you to stub the global TableLocator just to inject a mock.

CakePHP 5.3 changes the game with Inversion of Control. With the framework currently in its Release Candidate (RC) stage and a stable release expected soon, now is the perfect time to explore these architectural improvements. By using the new TableContainer as a delegate for your PSR-11 container, tables can now be automatically injected directly into your constructors. This shift to explicit dependencies makes your code cleaner, fully type-hinted, and ready for modern testing standards.

The Old Way (Hidden Dependency):

public function execute() {
    $users = $this->fetchTable('Users'); // Where did this come from?
}

The 5.3 Way (Explicit Dependency):

public function __construct(protected UsersTable $users) {} 

public function execute() {
    $this->users->find(); // Explicit and testable.
}


Enabling the Delegate

Open src/Application.php and update the services() method by delegating table resolution to the TableContainer.

// src/Application.php
use Cake\ORM\TableContainer;

public function services(ContainerInterface $container): void
{
    // Register the TableContainer as a delegate
    $container->delegate(new TableContainer());
}


How it works under the hood

When you type-hint a class ending in Table (e.g., UsersTable), the main PSR-11 container doesn't initially know how to instantiate it. Because you've registered a delegate, it passes the request to the TableContainer, which then:

  1. Validates: It verifies the class name and ensures it is a subclass of \Cake\ORM\Table.
  2. Locates: It uses the TableLocator to fetch the correct instance (handling all the usual CakePHP ORM configuration behind the scenes).
  3. Resolves: It returns the fully configured Table object back to the main container to be injected.

Note: The naming convention is strict. The TableContainer specifically looks for the Table suffix. If you have a custom class that extends the base Table class but is named UsersRepository, the delegate will skip it, and the container will fail to resolve the dependency.

Practical Example: Cleaner Services

Now, your domain services no longer need to know about the LocatorAwareTrait. They simply ask for what they need.

namespace App\Service;

use App\Model\Table\UsersTable;

class UserManagerService
{
    // No more TableRegistry::get() or $this->fetchTable()
    public function __construct(
        protected UsersTable $users
    ) {}

    public function activateUser(int $id): void
    {
        $user = $this->users->get($id);
        // ... logic
    }
}

Next, open src/Application.php and update the services() method by delegating table resolution to the TableContainer.

// src/Application.php
use App\Model\Table\UsersTable;
use App\Service\UserManagerService;
use Cake\ORM\TableContainer;

public function services(ContainerInterface $container): void
{
    // Register the TableContainer as a delegate
    $container->delegate(new TableContainer());

    // Register your service with the table as constructor argument  
    $container  
        ->add(UserManagerService::class)  
        ->addArgument(UsersTable::class);
}


Why this is a game changer for Testing

Because the table is injected via the constructor, you can now swap it for a mock effortlessly in your test suite without touching the global state of the application.

$mockUsers = $this->createMock(UsersTable::class);
$service = new UserManagerService($mockUsers); // Pure injection!


Conclusion: Small Change, Big Impact

At first glance, adding a single line to your Application::services() method might seem like a minor update. However, TableContainer represents a significant shift in how we approach CakePHP architecture.

By delegating table resolution to the container, we gain:

  • True Type-Safety: Your IDE and static analysis tools now recognize the exact Table class being used. This is a massive win for PHPStan users—no more "Call to an undefined method" errors or messy @var docblock workarounds just to prove to your CI that a method exists.
  • Zero-Effort Mocking: Testing a service no longer requires manipulating the global TableRegistry state. Simply pass a mock object into the constructor and move on.
  • Standardization: Your CakePHP code now aligns with modern PHP practices found in any PSR-compliant ecosystem, making your application more maintainable and easier for new developers to understand.

If you plan to upgrade to CakePHP 5.3 upon its release, this is one of the easiest wins for your codebase. It’s time to stop fetching your tables and start receiving them.

This article is part of the CakeDC Advent Calendar 2025 (December 23rd, 2025)

Latest articles

Pagination of multiple queries in CakePHP

Pagination of multiple queries in CakePHP

A less typical use case for pagination in an appication is the need to paginate multiples queries. In CakePHP you can achieve this with pagination scopes.

Users list

Lest use as an example a simple users list. // src/Controller/UsersController.php class UsersController extends AppController { protected array $paginate = [ 'limit' => 25, ]; public function index() { // Default model pagination $this->set('users', $this->paginate($this->Users)); } } // templates/Users/index.php <h2><?= __('Users list') ?>/h2> <table> <thead> <tr> <th><?= $this->Paginator->sort('name', __('Name')) ?></th> <th><?= $this->Paginator->sort('email', __('Email')) ?></th> <th><?= $this->Paginator->sort('active', __('Active')) ?></th> </tr> </thead> <tbody> <?php foreach ($users as $user): ?> <tr> <td><?= h($user->name) ?></td> <td><?= h($user->email) ?></td> <td><?= $user->active ? 'Yes' : 'No' ?></td> </tr> <?php endforeach; ?> </tbody> </table> <?= $this->Paginator->counter() ?> <?= $this->Paginator->prev('« Previous') ?> <?= $this->Paginator->numbers() ?> <?= $this->Paginator->next('Next »') ?>

Pagination of multiple queries

Now, we want to display two paginated tables, one with the active users and the other with the inactive ones. // src/Controller/UsersController.php class UsersController extends AppController { protected array $paginate = [ 'Users' => [ 'scope' => 'active_users', 'limit' => 25, ], 'InactiveUsers' => [ 'scope' => 'inactive_users', 'limit' => 10, ], ]; public function index() { $activeUsers = $this->paginate( $this->Users->find()->where(['active' => true]), [scope: 'active_users'] ); // Load an additional table object with the custom alias set in the paginate property $inactiveUsersTable = $this->fetchTable('InactiveUsers', [ 'className' => \App\Model\Table\UsersTable::class, 'table' => 'users', 'entityClass' => 'App\Model\Entity\User', ]); $inactiveUsers = $this->paginate( $inactiveUsersTable->find()->where(['active' => false]), [scope: 'inactive_users'] ); $this->set(compact('users', 'inactiveUsers')); } } // templates/Users/index.php <?php // call `setPaginated` first with the results to be displayed next, so the paginator use the correct scope for the links $this->Paginator->setPaginated($users); ?> <h2><?= __('Active Users') ?>/h2> <table> <thead> <tr> <th><?= $this->Paginator->sort('name', __('Name')) ?></th> <th><?= $this->Paginator->sort('email', __('Email')) ?></th> <th><?= $this->Paginator->sort('active', __('Active')) ?></th> </tr> </thead> <tbody> <?php foreach ($users as $user): ?> <tr> <td><?= h($user->name) ?></td> <td><?= h($user->email) ?></td> <td><?= $user->active ? 'Yes' : 'No' ?></td> </tr> <?php endforeach; ?> </tbody> </table> <?= $this->Paginator->counter() ?> <?= $this->Paginator->prev('« Previous') ?> <?= $this->Paginator->numbers() ?> <?= $this->Paginator->next('Next »') ?> <?php // call `setPaginated` first with the results to be displayed next, so the paginator use the correct scope for the links $this->Paginator->setPaginated($inactiveUsers); ?> <h2><?= __('Inactive Users') ?>/h2> <table> <thead> <tr> <th><?= $this->Paginator->sort('name', __('Name')) ?></th> <th><?= $this->Paginator->sort('email', __('Email')) ?></th> <th><?= $this->Paginator->sort('active', __('Active')) ?></th> </tr> </thead> <tbody> <?php foreach ($inactiveUsers as $inactiveUser): ?> <tr> <td><?= h($inactiveUser->name) ?></td> <td><?= h($inactiveUser->email) ?></td> <td><?= $inactiveUser->active ? 'Yes' : 'No' ?></td> </tr> <?php endforeach; ?> </tbody> </table> <?= $this->Paginator->counter() ?> <?= $this->Paginator->prev('« Previous') ?> <?= $this->Paginator->numbers() ?> <?= $this->Paginator->next('Next »') ?> And with this you have two paginated tables in the same request.

The new CakePHP RateLimitMiddleware

This article is part of the CakeDC Advent Calendar 2025 (December 21st 2025) Rate limiting a specific endpoint of your application can be a life saver. Sometimes you can't optimize the endpoint and it'll be expensive in time or CPU, or the endpoint has a business restriction for a given user. In the past, I've been using https://github.com/UseMuffin/Throttle a number of times to provide rate limiting features to CakePHP. Recently, I've been watching the addition of the RateLimitMiddleware to CakePHP 5.3, I think it was a great idea to incorporate these features into the core and I'll bring you a quick example about how to use it in your projects. Let's imagine you have a CakePHP application with an export feature that will take some extra CPU to produce an output, you want to ensure the endpoint is not abused by your users. In order to limit the access to the endpoint, add the following configuration to your config/app.php // define a cache configuration, Redis could be a good option for a fast and distributed approach 'rate_limit' => [ 'className' => \Cake\Cache\Engine\RedisEngine::class, 'path' => CACHE, 'url' => env('CACHE_RATE_LIMIT_URL', null), ], Then, in your src/Application.php middleware method, create one or many configurations for your rate limits. The middleware allows a lot of customization, for example to select the strategy, or how are you going to identify the owner of the rate limit. ->add(new RateLimitMiddleware([ 'strategy' => RateLimitMiddleware::STRATEGY_FIXED_WINDOW, 'identifier' => RateLimitMiddleware::IDENTIFIER_IP, 'limit' => 5, 'window' => 10, 'cache' => 'rate_limit', 'skipCheck' => function ($request) { return !( $request->getParam('controller') === 'Reports' && $request->getParam('action') === 'index' ); } ])) In this particular configuration we are going to limit the access to the /reports/index endpoint (we skip everything else) to 5 requests every 10 seconds. You can learn more about the middleware configuration here https://github.com/cakephp/docs/pull/8063 while the final documentation is being finished. This article is part of the CakeDC Advent Calendar 2025 (December 21st 2025)

Real-Time Notifications? You Might Not Need WebSockets

This article is part of the CakeDC Advent Calendar 2025 (December 20th 2025) As PHP developers, when we hear "real-time," our minds immediately jump to WebSockets. We think of complex setups with Ratchet, long-running server processes, and tricky Nginx proxy configurations. And for many applications (like live chats or collaborative editing) WebSockets are absolutely the right tool. But, if you don't need all that complexity or if you just want to push data from your server to the client? Think of a new notification, a "users online" counter, or a live dashboard update. For these one-way-street use cases, WebSockets are often overkill. Enter Server-Sent Events (SSE). It's a simple, elegant, and surprisingly powerful W3C standard that lets your server stream updates to a client over a single, long-lasting HTTP connection.

SSE vs. WebSockets: The Showdown

The most important difference is direction.
  • WebSockets (WS): Bidirectional. The client and server can both send messages to each other at any time. It's a two-way conversation.
  • Server-Sent Events (SSE): Unidirectional. Only the server can send messages to the client. It's a one-way broadcast.
This single difference has massive implications for simplicity and implementation.
Feature Server-Sent Events (SSE) WebSockets (WS)
Direction Unidirectional (Server ➔ Client) Bidirectional (Client ⟺ Server)
Protocol Just plain HTTP/S A new protocol (ws://, wss://)
Simplicity High. simple API, complex ops at scale Low. Requires a special server.
Reconnection Automatic! The browser handles it. Manual. You must write JS to reconnect.
Browser API Native EventSource object. Native WebSocket object.
Best For Notifications, dashboards, live feeds. Live chats, multiplayer games, co-editing.
Pros for SSE:
  • It's just HTTP. No new protocol, no special ports.
  • Automatic reconnection is a life-saver.
  • The server-side implementation can be a simple controller action.
Cons for SSE:
  • Strictly one-way. The client can't send data back on the same connection.
  • Some older proxies or servers might buffer the response, which can be tricky.
Infrastructure Note: Since SSE keeps a persistent connection open, each active client will occupy one PHP-FPM worker. For high-traffic applications, ensure your server is configured to handle the concurrent load or consider a non-blocking server like RoadRunner. Additionally, using HTTP/2 is strongly recommended to bypass the 6-connection-per-domain limit found in older HTTP/1.1 protocols

The Implementation: A Smart, Reusable SSE System in CakePHP

We're not going to build a naive while(true) loop that hammers our database every 2 seconds. That's inefficient. Instead, we'll build an event-driven system. The while(true) loop will only check a cache key. This is lightning-fast. A separate "trigger" class will update that cache key's timestamp only when a new notification is actually created. This design is clean, decoupled, and highly performant.
Note: This example uses CakePHP, but the principles (a component, a trigger, and a controller) can be adapted to any framework like Laravel or Symfony.

1. The Explicit SseTrigger Class

First, we need a clean, obvious way to "poke" our SSE stream. We'll create a simple class whose only job is to update a cache timestamp. This is far better than a "magic" Cache::write() call hidden in a model. src/Sse/SseTrigger.php <?php namespace App\Sse; use Cake\Cache\Cache; /** * Provides an explicit, static method to "push" an SSE event. * This simply updates a cache key's timestamp, which the * SseComponent is watching. */ class SseTrigger { /** * Pushes an update for a given SSE cache key. * * @param string $cacheKey The key to "touch". * @return bool */ public static function push(string $cacheKey): bool { // We just write the current time. The content doesn't // matter, only the timestamp. return Cache::write($cacheKey, microtime(true)); } }

CRITICAL PERFORMANCE WARNING: The PHP-FPM Bottleneck

In a standard PHP-FPM environment, each SSE connection is synchronous and blocking. This means one active SSE stream = one locked PHP-FPM worker. If your max_children setting is 50, and 50 users open your dashboard, your entire website will stop responding because there are no workers left to handle regular requests. How to mitigate this: Dedicated Pool: Set up a separate PHP-FPM pool specifically for SSE requests. Go Asynchronous: Use a non-blocking server like RoadRunner, Swoole or FrankenPHP. These can handle thousands of concurrent SSE connections with minimal memory footprint. HTTP/2: Always serve SSE over HTTP/2 to bypass the browser's 6-connection limit per domain.

2. The SseComponent (The Engine)

This component encapsulates all the SSE logic. It handles the loop, the cache-checking, the CallbackStream, and even building the final Response object. The controller will be left perfectly clean. To handle the stream, we utilize CakePHP's CallbackStream. Unlike a standard response that sends all data at once, CallbackStream allows us to emit data in chunks over time. It wraps our while(true) loop into a PSR-7 compliant stream, enabling the server to push updates to the browser as they happen without terminating the request. src/Controller/Component/SseComponent.php <?php namespace App\Controller\Component; use Cake\Controller\Component; use Cake\Http\CallbackStream; use Cake\Cache\Cache; use Cake\Http\Response; class SseComponent extends Component { protected $_defaultConfig = [ 'poll' => 2, // How often to check the cache (in seconds) 'eventName' => 'message', // Default SSE event name 'heartbeat' => 30, // Keep-alive to prevent proxy timeouts ]; /** * Main public method. * Builds the stream and returns a fully configured Response. */ public function stream(callable $dataCallback, string $watchCacheKey, array $options = []): Response { $stream = $this->_buildStream($dataCallback, $watchCacheKey, $options); // Get and configure the controller's response $response = $this->getController()->getResponse(); $response = $response ->withHeader('Content-Type', 'text/event-stream') ->withHeader('Cache-Control', 'no-cache') ->withHeader('Connection', 'keep-alive') ->withHeader('X-Accel-Buffering', 'no') // For Nginx: disable response buffering ->withBody($stream); return $response; } /** * Protected method to build the actual CallbackStream. */ protected function _buildStream(callable $dataCallback, string $watchCacheKey, array $options = []): CallbackStream { $config = $this->getConfig() + $options; return new CallbackStream(function () use ($dataCallback, $watchCacheKey, $config) { set_time_limit(0); $lastSentTimestamp = null; $lastHeartbeat = time(); while (true) { if (connection_aborted()) { break; } // 1. THE FAST CHECK: Read the cache. $currentTimestamp = Cache::read($watchCacheKey); // 2. THE COMPARE: Has it been updated? if ($currentTimestamp > $lastSentTimestamp) { // 3. THE SLOW CHECK: Cache is new, so run the data callback. $data = $dataCallback(); // 4. THE PUSH: Send the data. echo "event: " . $config['eventName'] . "\n"; echo "data: " . json_encode($data) . "\n\n"; $lastSentTimestamp = $currentTimestamp; $lastHeartbeat = time(); } else if (time() - $lastHeartbeat > $config['heartbeat']) { // 5. THE HEARTBEAT: Send a comment to keep connection alive. echo ": \n\n"; $lastHeartbeat = time(); } if (ob_get_level() > 0) { ob_flush(); } flush(); // Wait before the next check sleep($config['poll']); } }); } }

3. Connecting the Logic (Model & Controller)

First, we use our SseTrigger in the afterSave hook of our NotificationsTable. This makes it clear: "After saving a notification, push an update." src/Model/Table/NotificationsTable.php (Partial) use App\Sse\SseTrigger; // Don't forget to import! public function afterSave(EventInterface $event, Entity $entity, ArrayObject $options) { // Check if the entity has a user_id if ($entity->has('user_id') && !empty($entity->user_id)) { // Build the user-specific cache key $userCacheKey = 'notifications_timestamp_user_' . $entity->user_id; // Explicitly trigger the push! SseTrigger::push($userCacheKey); } } Now, our controller action becomes incredibly simple. Its only jobs are to get the current user, define the data callback, and return the component's stream. src/Controller/NotificationsController.php <?php namespace App\Controller; use App\Controller\AppController; use Cake\Http\Exception\ForbiddenException; class NotificationsController extends AppController { public function initialize(): void { parent::initialize(); $this->loadComponent('Sse'); $this->loadComponent('Authentication.Authentication'); } public function stream() { $this->autoRender = false; // 1. Get authenticated user $identity = $this->Authentication->getIdentity(); if (!$identity) { throw new ForbiddenException('Authentication required'); } // 2. Define user-specific parameters $userId = $identity->get('id'); $userCacheKey = 'notifications_timestamp_user_' . $userId; // 3. Define the data callback (what to run when there's an update) $dataCallback = function () use ($userId) { return $this->Notifications->find() ->where(['user_id' => $userId, 'read' => false]) ->order(['created' => 'DESC']) ->limit(5) ->all(); }; // 4. Return the stream. That's it! return $this->Sse->stream( $dataCallback, $userCacheKey, [ 'eventName' => 'new_notification', // Custom event name for JS 'poll' => 2 ] ); } }

4. The Frontend (The Easy Part)

Thanks to the native EventSource API, the client-side JavaScript is trivial. No libraries. No complex connection management. <script> // 1. Point to your controller action const sseUrl = '/notifications/stream'; const eventSource = new EventSource(sseUrl); // 2. Listen for your custom event eventSource.addEventListener('new_notification', (event) => { console.log('New data received!'); const notifications = JSON.parse(event.data); // Do something with the data... // e.g., update a <ul> list or a notification counter updateNotificationBell(notifications); }); // 3. (Optional) Handle errors eventSource.onerror = (error) => { console.error('EventSource failed:', error); // The browser will automatically try to reconnect. }; // (Optional) Handle the initial connection eventSource.onopen = () => { console.log('SSE connection established.'); }; </script>

Ideas for Your Projects

You can use this exact pattern for so much more than just notifications:
  • Live Admin Dashboard: A "Recent Sales" feed or a "Users Online" list that updates automatically.
  • Activity Feeds: Show "John recently commented..." in real-time.
  • Progress Indicators: For a long-running background process (like video encoding), push status updates ("20% complete", "50% complete", etc.).
  • Live Sports Scores: Push new scores as they happen.
  • Stock or Crypto Tickers: Stream new price data from your server.

When NOT to Use SSE: Know Your Limits

While SSE is an elegant solution for many problems, it isn't a silver bullet. You should avoid SSE and stick with WebSockets or standard Polling when:
  • True Bidirectional Communication is Required: If your app involves heavy "back-and-forth" (like a fast-paced multiplayer game or a collaborative whiteboarding tool), WebSockets are the correct choice.
  • Binary Data Streams: SSE is a text-based protocol. If you need to stream raw binary data (like audio or video frames), WebSockets or WebRTC are better suited.
  • Legacy Browser Support (IE11): If you must support older browsers that lack EventSource and you don't want to rely on polyfills, SSE will not work.
  • Strict Connection Limits: If you are on a restricted shared hosting environment with very few PHP-FPM workers and no support for HTTP/2, the persistent nature of SSE will quickly exhaust your server's resources.

Conclusion

WebSockets are a powerful tool, but they aren't the only tool. For the wide array of use cases that only require one-way, server-to-client communication, Server-Sent Events are a simpler, more robust, and more maintainable solution. It integrates perfectly with the standard PHP request cycle, requires no extra daemons, and is handled natively by the browser. So the next time you need real-time updates, ask yourself: "Do I really need a two-way conversation?" If the answer is no, give SSE a try. This article is part of the CakeDC Advent Calendar 2025 (December 20th 2025)

We Bake with CakePHP