Working with Mutable and Immutable DateTime in PHP

Published on by

Working with Mutable and Immutable DateTime in PHP image

Mutable dates can be the source of confusion and unexpected bugs in your code. My goal isn’t to tell you that DateTime is evil because it’s mutable, but to consider the tradeoffs and benefits of using mutable versus immutable DateTime objects. Either approach warrants a good test suite and an awareness of how modifier methods affect your date objects.

Until recently, I wasn’t even aware that PHP offers a counterpart to the DateTime class: DateTimeImmutable. The DateTimeIummtable class works just like the DateTime class, except that it never modifies itself, but returns a new object instead. So if you know how to work with DateTime, you immediately can work with DateTimeImmutable.

Working with Mutable DateTime Objects in PHP

Fortunately for us mere mortals, we can further abstract away these classes and work with libraries like Carbon. Later on, I’ll introduce you to a similar immutable library on top of DateTimeIummtable.

Carbon extends the mutable variety of DateTime which means that as you pass around a Carbon instance any modifier calls to it (i.e., addDay()) will result in change:

$person = Person::find(1);
echo $person->born // 1998-05-29 02:35:53
$person->born->addDay(1);
echo $person->born // 1998-05-30 02:35:53
$person->save();

In the context of an Eloquent model, this makes perfect sense. Otherwise, we’d have this weird assignment any time that we want to update a date using the immutable approach:

// This code doesn't work, it's what it would look like if Carbon instances were immutable
$newBirthday = $person->born->addDay(1);
$person->born = $newBirthday;
 
// Or...
$person->born = $person->born->addDay(1);

If you intend to do some comparison checking that takes modifications, you’d need to make a copy of this date to avoid mutating the original attribute. For example, this will mutate the model attribute:

function birthdayIsTomorrow($birthday) {
return $birthday->addDay(1)->isTomorrow();
}
 
// Mutation takes place...
if (birthdayIsTomorrow($person->born)) {
 
}
 
// No mutation takes place...
if (birthdayIsTomorrow($person->born->copy())) {
 
}
 
// Via clone, no mutation takes place...
if (birthdayIsTomorrow(clone $person->born)) {
 
}

The other interesting thing here is that if your code mutates the date, but you don’t save() the model, you might have a weird edge-case bug that’s hard to track down. The big takeaway here is to be aware of how code mutates your dates, and pass a copy of the date instead of a whole model to a method that needs to make modifications to the date.

I am not trying to argue that using the mutable library like Carbon is wrong; I am focusing on demonstrating how this style of object behaves and defensive techniques you must apply to avoid unexpected mutation.

Working with Immutable DateTime Objects in PHP

If you like working with Carbon, and you want to experiment with an immutable version that has a similar API, you might be interested in the Chronos library by the CakePHP foundation. Chronos was initially based off of Carbon, and is a stand-alone library without any external dependencies outside of PHP version ^5.5.9|^7.

Additionally, Chronos contains mutable date/time variants, totaling in five classes:

  • Cake\Chronos\Chronos is an immutable date and time object.
  • Cake\Chronos\Date is an immutable date object.
  • Cake\Chronos\MutableDateTime is a mutable date and time object.
  • Cake\Chronos\MutableDate is a mutable date object.
  • Cake\Chronos\ChronosInterval is an extension to the DateInterval object.

Using Chronos in the previous code example, the date object isn’t concerned with mutation because any change returns a new object:

if (birthdayIsTomorrow($person->born)) {
// Immutable, $person->born would equal `today` still
}

Every time you modify an object, a new copy is returned, making your code free from order-based dependency issues. Take the following example:

// i.e., 2018-05-29 04:23:01.342143
$meeting = \Cake\Chronos\Chronos::tomorrow();
$meeting->addDay(1); // Returns a new object
 
// No mutation, it returns the original 2018-05-29...
return $meeting;

To work with immutable dates, you need to replace the variable when working with modifiers:

$meeting = \Cake\Chronos\Chronos::tomorrow();
$meeting = $meeting->addDay(1);
 
// Returns 2018-05-30...
return $meeting

Even if you want to reset the date to the start of the day, you would need to do the same, or chain it to the original assignment:

// Assignment
$meeting = \Cake\Chronos\Chronos::tomorrow();
$meeting = $meeting->addDay(1);
$meeting = $meeting->startOfDay();
 
// Chain the original
// i.e., 2018-05-31 00:00:00.000000
$meeting = \Cake\Chronos\Chronos::tomorrow()
->addDay(1)
->startOfDay();

Immutability makes you enforce intentional changes by explicitly reassigning a date object, and you don’t have to fear passing around the original object.

Learn More

Although the difference feels subtle, using immutable date objects can give you confidence that passing around a date isn’t going to cause a mutation to the original object, unless you explicitly reassign.

I am not trying to say that one style is better than another, I am pointing out that I believe learning about PHP’s DateTimeImmutable can help clarify some of the defensive techniques that immutable dates give your code.

With that in mind, using Carbon, you need to be aware of any dates you intend to pass around to other methods for comparisons or other logic. I would suggest always copying the DateTime instance to avoid mutation, and be aware of potential points of mutability in your dates that could create unexpected results.

If you want to experiment more with an immutable DateTime library with a nice API like Carbon’s, check out the Chronos documentation.

Paul Redmond photo

Staff writer at Laravel News. Full stack web developer and author.

Cube

Laravel Newsletter

Join 40k+ other developers and never miss out on new tips, tutorials, and more.

Laravel Forge logo

Laravel Forge

Easily create and manage your servers and deploy your Laravel applications in seconds.

Laravel Forge
Tinkerwell logo

Tinkerwell

The must-have code runner for Laravel developers. Tinker with AI, autocompletion and instant feedback on local and production environments.

Tinkerwell
No Compromises logo

No Compromises

Joel and Aaron, the two seasoned devs from the No Compromises podcast, are now available to hire for your Laravel project. ⬧ Flat rate of $7500/mo. ⬧ No lengthy sales process. ⬧ No contracts. ⬧ 100% money back guarantee.

No Compromises
Laravel Idea for PhpStorm logo

Laravel Idea for PhpStorm

Ultimate PhpStorm plugin for Laravel developers, delivering lightning-fast code completion, intelligent navigation, and powerful generation tools to supercharge productivity.

Laravel Idea for PhpStorm
Kirschbaum logo

Kirschbaum

Providing innovation and stability to ensure your web application succeeds.

Kirschbaum
Shift logo

Shift

Running an old Laravel version? Instant, automated Laravel upgrades and code modernization to keep your applications fresh.

Shift
Bacancy logo

Bacancy

Supercharge your project with a seasoned Laravel developer with 4-6 years of experience for just $2500/month. Get 160 hours of dedicated expertise & a risk-free 15-day trial. Schedule a call now!

Bacancy
Lucky Media logo

Lucky Media

Get Lucky Now - the ideal choice for Laravel Development, with over a decade of experience!

Lucky Media
Lunar: Laravel E-Commerce logo

Lunar: Laravel E-Commerce

E-Commerce for Laravel. An open-source package that brings the power of modern headless e-commerce functionality to Laravel.

Lunar: Laravel E-Commerce
LaraJobs logo

LaraJobs

The official Laravel job board

LaraJobs
SaaSykit: Laravel SaaS Starter Kit logo

SaaSykit: Laravel SaaS Starter Kit

SaaSykit is a Multi-tenant Laravel SaaS Starter Kit that comes with all features required to run a modern SaaS. Payments, Beautiful Checkout, Admin Panel, User dashboard, Auth, Ready Components, Stats, Blog, Docs and more.

SaaSykit: Laravel SaaS Starter Kit
Supercharge Your SaaS Development with FilamentFlow: The Ultimate Laravel Filament Boilerplate logo

Supercharge Your SaaS Development with FilamentFlow: The Ultimate Laravel Filament Boilerplate

Build your SaaS application in hours. Out-of-the-box multi-tenancy and seamless Stripe integration. Supports subscriptions and one-time purchases, allowing you to focus on building and creating without repetitive setup tasks.

Supercharge Your SaaS Development with FilamentFlow: The Ultimate Laravel Filament Boilerplate
JetShip - Laravel Starter Kit logo

JetShip - Laravel Starter Kit

A Laravel SaaS Boilerplate and a starter kit built on the TALL stack. It includes authentication, payments, admin panels, and more. Launch scalable apps fast with clean code, seamless deployment, and custom branding.

JetShip - Laravel Starter Kit
Rector logo

Rector

Your partner for seamless Laravel upgrades, cutting costs, and accelerating innovation for successful companies

Rector
MongoDB logo

MongoDB

Enhance your PHP applications with the powerful integration of MongoDB and Laravel, empowering developers to build applications with ease and efficiency. Support transactional, search, analytics and mobile use cases while using the familiar Eloquent APIs. Discover how MongoDB's flexible, modern database can transform your Laravel applications.

MongoDB

The latest

View all →
Streamlining Route Parameters in Laravel Using URL Defaults image

Streamlining Route Parameters in Laravel Using URL Defaults

Read article
Flexible Docker Images with PHP INI Environment Variables image

Flexible Docker Images with PHP INI Environment Variables

Read article
Dynamic Form Validation in Laravel with prohibited_if image

Dynamic Form Validation in Laravel with prohibited_if

Read article
Add Approvals to Your Laravel Application image

Add Approvals to Your Laravel Application

Read article
Enhancing Data Processing with Laravel's transform() Method image

Enhancing Data Processing with Laravel's transform() Method

Read article
Get Xdebug Working With Docker and PHP 8.4 in One Minute image

Get Xdebug Working With Docker and PHP 8.4 in One Minute

Read article