Working with Mutable and Immutable DateTime in PHP
Published on by Paul Redmond
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.