CakeDC Blog

TIPS, INSIGHTS AND THE LATEST FROM THE EXPERTS BEHIND CAKEPHP

Felix Geisendörfer - Recipies for successful CakePHP projects

Felix liked to Get Things Done™. And through experience and what became an interactive idea and experience sharing productivity session, he explained mechanisms and methods that he has used to achieve the best results for projects in the shortest time possible.

Communication. While this means your team should be in contact, and that those contact points should be quality communication, it doesn't mean that instant communication is a requirement. Communication mechanisms would ideally be: decentralised and work in an offline capacity (at least for partial functionality).

Return on investment is an interesting statistic to consider when responding to or creating a new item of communication. Provide a concise message. Enough to ensure the intention of the communication is clear, and ambiguity is reduced if not eliminated. Email is a great tool, especially for the following: Timezone differences, announcements, spawning debates that require discussion, emergency notifications / reports, mailing lists, shared email accounts and automated reporting / information.

Using Email over an instant messaging mechanism for spawning debates allows contributors to formulate a constructed response. This can assist the better understanding of some ones input to the discussions, as instant messaging can be difficult for items that require discussion.

Instant messaging has good and bad traits:

  1. Good Stuff
    1. Instant
    2. Group Chats / conference calls
    3. Varying methods of communication
    4. Various formats (text, voice, video)
  2. Bad Stuff
    1. Distracting (interrupts workflow)
    2. History tracking / compatibility
    3. Citations / logs
Task management helps keep projects on track. However the truth is that there is no overall solution. We do the best we can to manage all the information we need to be successful, through a variety of tools.

Problems that exist are:

  1. Getting tasks into the system (May be the laziness of users)
  2. Tracking tasks that manage to make it into the system
  3. Getting those tasks done

Tools available:

  1. Pen and Paper (plain text files)
  2. OmniFocus (Mac Only)
  3. Lighthouse / TheChaw
One of the CakeFest attendees suggested post-it notes on a wall, so that the tam involved in pursuing the tasks can have some physical interaction with them, making the experience more productive and fun.

So with this in mind, Felix quickly went over what has worked for him and his company:

  1. Check emails twice a day only.
  2. Turn off instant messaging tools in the morning
  3. Set clear distinct goals for the day, and achieve those goals

How to fail at unit testing. Felix described some common myths about unit testing, how he feels failing is possible and how to improve your approach.

Failed unit testing can come from factors such as: Attempting to reach 100% code coverage all the time, misunderstanding test driven development and expecting that all developers / users can write unit tests.

Success can be achieved by approaching projects with a top-down approach, incorporating performance tests and re-factoring code.

Continuous integration was presented in a basic format, going through the setup that Felix has found useful, making use of git post-receive hooks, and parsing of results to send notifications when necessary. In terms of increasing productivity and performance overall, Felix has begun testing Pair programming, where there is one computer for two people, and the development process is discussed ongoing, meaning that a lot of bugs an individual would miss are caught by the secondary developer on the first code pass.

Virtualization though open source and free products like VirtualBox and VMWare Server are worthwhile investigating for cheap scaling testing during development.

Version control was introduced, referencing the change of CakePHP to git from subversion, pointing out the benefits including: decentralization, can work offline, can work semi-online though the use of adhoc networks, its very fast to operate and its more intelligent with the storage of information. Following this, a detailed example of three separate working repositories was demonstrated.

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.

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)

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)

We Bake with CakePHP