CakeDC Blog

TIPS, INSIGHTS AND THE LATEST FROM THE EXPERTS BEHIND CAKEPHP

New exciting features in PHP 8.4 Part III

This article is part of the CakeDC Advent Calendar 2024 (December 16th 2024)

In this article, we will continue to explore the new features and improvements added in the latest version of PHP 8.4.

This is the third article in this series, we encourage you to read the first and second article from the series.

In this release, we have received several long-awaited improvements, improved functionality, and a modern approach to common tasks. These few seem to be the most interesting:

  • Lazy Objects
  • Object API for BCMath

Lazy Objects

Lazy objects are objects that are initialized when the state of the object is observed or modified.

The use of this type of objects can take place in several scenarios:

  1. Let's assume that you have an object that is expensive to create and may not always be used. For example, when you have an Invoice object that has a LineItems property containing a large amount of data retrieved from the database. If the user asks to display a list of invoices without their content, Lazy Object functionality will prevent unnecessary waste of resources.

  2. Let's assume that you have an object that is expensive to create and you would like to delay its initialization until other expensive operations are performed. For example, you are preparing user data for export, but using Lazy Objects you can delay loading data from the database and perform, for example, authentication to an external API and preparation tasks, and only during export the data from the database will be loaded.

Lazy objects can be created in two strategies:

  1. Ghost Objects - such lazy objects are indistinguishable from normal objects and can be used without knowing that they are lazy.
  2. Virtual Proxies - in this case, the lazy object and the real instance are separate identities, so additional tasks must be performed when accessing the Virtual Proxy.

Creating Ghost Objects

Lazy ghost strategy should be used when we have control over the instatiation and initialization of an object. Lazy ghost is indistinguishable from a real instance of the object.

class LazyGhostExample
{
    public function __construct(public string $property)
    {
        echo "LazyGhost initialized\n";
    }
}

$reflectionClass = new \ReflectionClass(LazyGhostExample::class);
$newLazyGhost = $reflectionClass->newLazyGhost(function (LazyGhostExample $lazyGhostExample) {
    $lazyGhostExample->__construct('example');
});

// the object is not initialized yet
var_dump($newLazyGhost);

// the object is of class LazyGhostExample
var_dump(get_class($newLazyGhost));

// the object is initialized on the first observation (reading the property)
var_dump($newLazyGhost->property);

The above example will output:

lazy ghost object(LazyGhostExample)#15 (0) {
  ["property"]=>
  uninitialized(string)
}
string(28) "LazyGhostExample"
LazyGhost initialized
string(7) "example"

Creating Virtual Proxies

Lazy proxies after initialization are intermediaries to the real object instance, each operation on the proxy is redirected to the real object. This approach is good when we do not control the object initialization process. In the example below, we see that we are returning a new instance of the object, thus we do not interfere with what is happening in the constructor.

class LazyProxyExample
{
    public function __construct(public string $property)
    {
        echo "LazyGhost initialized\n";
    }
}

$reflectionClass = new \ReflectionClass(LazyProxyExample::class);
$newLazyProxy = $reflectionClass->newLazyProxy(
    function (LazyProxyExample $lazyProxyExample): LazyProxyExample {
        return new LazyProxyExample('example');
    }
);

// the object is not initialized yet
var_dump($newLazyProxy);

// the object is of class LazyGhostExample
var_dump(get_class($newLazyProxy));

// the object is initialized on the first observation (reading the property)
var_dump($newLazyProxy->property);

The above example will output:

lazy proxy objectLazyProxyExample)#15 (0) {
  ["property"]=>
  uninitialized(string)
}
string(28) "LazyProxyExample"
LazyGhost initialized
string(7) "example"

What triggers the initialization of Lazy Objects

Lazy Objects are initialized when one of the following operations occurs:

  • reading or writing a property
  • testing whether a property is set or unsetting it
  • reading, changing, or listing a property using the ReflectionProperty and ReflectionObject classes
  • serializing an object or cloning it
  • iterating through an object using foreach if the object does not implement Iterator or IteratorAggregate

Object API for BCMath

Another new feature is an object oriented way of performing mathematical operations on numbers with arbitrary precision numbers. The new class BcMatch\Number is used for this purpose. Below is an example of how to use objects of this class for mathematical operations.

$pi = new BcMath\Number('3.14159');
$euler = new BcMath\Number('2.71828');

// we can just sum both instances
$sum1 = $pi + $euler;
var_dump($sum1);
// we can use chaining to do the same
$sum2 = $pi->add($euler);
var_dump($sum2);

// we can compare the objects
var_dump($pi > $euler);

// we also can compare using method chaining, it this case we will get results
// -1 if argument of compare is greater that the number instance
// 0 if the argument of compare is equal to number instance
// 1 if the argument of compare is greater than number instance
var_dump($euler->compare($pi));

This new class is not yet documented in the php documentatjo so is the complete list of methods that can be found in the BcMath\Number class:

namespace BcMath {
    /**
     * @since 8.4
     */
    final readonly class Number implements \Stringable
    {

        public readonly string $value;

        public readonly int $scale;

        public function __construct(string|int $num) {}

        public function add(Number|string|int $num, ?int $scale = null): Number {}

        public function sub(Number|string|int $num, ?int $scale = null): Number {}

        public function mul(Number|string|int $num, ?int $scale = null): Number {}

        public function div(Number|string|int $num, ?int $scale = null): Number {}

        public function mod(Number|string|int $num, ?int $scale = null): Number {}

        /** @return Number[] */
        public function divmod(Number|string|int $num, ?int $scale = null): array {}

        public function powmod(Number|string|int $exponent, Number|string|int $modulus, ?int $scale = null): Number {}

        public function pow(Number|string|int $exponent, ?int $scale = null): Number {}

        public function sqrt(?int $scale = null): Number {}

        public function floor(): Number {}

        public function ceil(): Number {}

        public function round(int $precision = 0, \RoundingMode $mode = \RoundingMode::HalfAwayFromZero): Number {}

        public function compare(Number|string|int $num, ?int $scale = null): int {}

        public function __toString(): string {}

        public function __serialize(): array {}

        public function __unserialize(array $data): void {}
    }
}

Conclusion

The above features greatly extend the capabilities of the PHP language.

In addition to these improvements, PHP 8.4 also offers a number of other minor improvements and additions, check the detailed changelog for more information

This article is part of the CakeDC Advent Calendar 2024 (December 16th 2024)

Latest articles

Goodbye to 2025!

Well bakers… another advent calendar is coming to an end. I hope you enjoyed all of the topics covered each day. We are also closing the year with so much gratitude.    2025 was the 20th year of CakePHP, can you believe it? We had an amazing year with our team, the community and the CakePHP core. It was great connecting with those who attended CakeFest in Madrid, and we hope to have the opportunity to see more of you in 2026.    I cannot let the year end without getting a little sentimental. There is no better way to say it… THANK YOU. Thank you to the team who worked so hard, the core team that keeps pumping out releases, and most of all … thank you to our clients that trust us with their projects. CakeDC is successful because of the strong relationships we build with our network, and we hope to continue working with all of you for many years.    There are a lot of great things still to come in year 21! Could 2026 will be bringing us CakePHP 6?! Considering 2 is rhe legal drinking age in the US, maybe CakePHP 6 should be beer cake? Delicious. Stay tuned to find out.    Before I go, I am leaving you with something special. A note from Larry!   As we close out this year, I just want to say thank you from the bottom of my heart. Twenty years ago, CakePHP started as a simple idea shared by a few of us who wanted to make building on the web easier and more enjoyable. Seeing how far it has come, and more importantly, seeing how many lives and careers it has impacted, is something I never take for granted. I am deeply grateful for our team, the core contributors, the community, and our clients who continue to believe in what we do. You are the reason CakePHP and CakeDC are still here, still growing, and still relevant after two decades. Here is to what we have built together, and to what is still ahead. Thank you for being part of this journey. Larry

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)

We Bake with CakePHP