Looking for more information on how to do PHP the right way? Check out PHP: The Right Way

Laravel News:
Working with Mutable and Immutable DateTime in PHP
May 30, 2018 @ 14:34:51

On the Laravel News site there's a tutorial posted showing how to work effectively with mutable and immutable DateTime functionality in PHP. The DateTime functionality has long been bundled with the language and offers powerful tools for working with dates, improving on what the basic date function provides.

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.

The article starts by talking about mutable DateTime objects and shows examples of using the Carbon date handling package as a layer on top of PHP's DateTime handling. It includes code examples of mutable objects. It then moves on to the immutable objects, covering the differences between the two complete with code examples. The post ends with a bit more information about mutable vs immutable and links to the Chronos documentation for more information on another date handling library.

tagged: datetime tutorial carbon package mutable immutable

Link: https://laravel-news.com/mutable-and-immutable-date-time-php

Jeff Madsen:
What’s all this “immutable date” stuff, anyway?
Sep 06, 2017 @ 15:18:42

Jeff Madsen has a post on his Medium blog sharing some of his thoughts about immutable DateTime types, what the difference is between mutable and immutable and "why you should care".

I’m going to show you the difference between the two using two popular Php DateTime libraries? - Carbon and Chronos, and then demonstrate the danger of using the mutable one of those.

You have probably used Carbon? - ?it is a wonderful library put together by Brian Nesbitt that takes all the pain out of working with dates. It has got one “short-coming”, if you will?- ?it is built on top of the DateTime object.

He gives an example of why this is a problem with Carbon (mutable) and how it's handled differently in Chronos (immutable). He makes the point that, unless your date values are immutable, you don't have any idea of they've changed elsewhere in the processing. He gives a more real-world example of working with immutable objects with a "user" model class and the "name" properties attached to it.

tagged: immutable date carbon chronos bug example code tutorial

Link: https://medium.com/@codebyjeff/whats-all-this-immutable-date-stuff-anyway-72d4130af8ce

Simon Holywell:
PHP and immutability - part two
Apr 04, 2017 @ 17:54:48

Simon Holywell has continued his series looking at immutability and PHP in part two of his series improving on the code and classes from the previous post.

In the last article we learnt how to create an immutable data structure in PHP. There were a few issues to work through, but we got there in the end. Now onto making the immutable class more useful and easier to create modified copies. Note that these are copies and not modifications, in-place, to the original objects.

He then moves on from the "simple" mutation method previously used (making a new immutable object when a property changes). When the property list starts getting more complex simple single value references no longer scale. He makes use of methods internal to the class to modify the values and return a new immutable instance with the updated value. He shows how to modify this to prevent the setting of unexpected properties and how to expand it out to allow the input of an array of values to update and how to handle required/optional property values.

tagged: immutability series part2 tutorial immutable object

Link: https://www.simonholywell.com/post/2017/04/php-and-immutability-part-two/

Simon Holywell:
PHP and immutability
Mar 22, 2017 @ 16:21:37

In a recent post to his site Simon Holywell covers immutability in PHP. PHP, by default, uses weak typing and doesn't support much in the way of immutability but Simon shows you a few ways you can get around this and make immutable objects you can use and extend.

Being a weakly typed dynamic language, PHP has not really had the concept of immutability built into it. We’ve seen the venerable define() and CONSTANTS of course, but they’re limited. Whilst PHP does ship with an immutable class as part of it’s standard library, DateTimeImmutable, there is no immediately obvious method to create custom immutable objects.

[...] It is possible to write your own immutables using some simple and sneaky PHP techniques though. We’re going to use a simplistic data requirement to make the examples in this article easier to follow. I’ll be using professional skateboarders and the tricks that they brought to the world.

He starts the article talking about immutability and how it relates back to the current (as of PHP 7) values supported in constants - scalars and arrays (no objects). He then starts on the code to create the base Immutable class that sets its values via the constructor. He then points out some of the common "work arounds" people use when trying to work with immutable objects and some techniques to help prevent it: the use of final, a "flag" preventing another constructor call, etc.

tagged: immutable tutorial technique php7 constant

Link: https://www.simonholywell.com/post/2017/03/php-and-immutability/

MyBuilder Tech Blog:
Designing Immutable Concepts with Transient Mutation in PHP
Dec 15, 2016 @ 15:46:11

The MyBuilder.com Tech blog has a new post from Edd Mann looking at designing immutable concepts in PHP with "transient mutation".

In a recent project we felt it beneficial to introduce the Money pattern. There are many good resources on this pattern, so I will delegate to those for further definition. We decided that encapsulating this into a immutable value object allowed for a cleaner API and removed the fear of any unexpected mutation bugs. However, we noticed a spike in memory and processor usage when wishing to perform many successive actions on such values i.e. summation.

In such a case, new ‘temporary’ Money objects would be instantiated upon each applied addition. As many of these objects were simply a stepping stone to generating the final result, they were just left for the Garbage collector to clean-up.

The idea of "transients" is something pulled from the Clojure language allowing for the mutation of the immutable object and returning a new immutable one....with with some controls, not free form mutation. He includes showing an example of a "Money" object that implements this concept including a "withMutable" method that handles a callback for the mutation operation.

tagged: immutable object transient mutation control tutorial

Link: http://tech.mybuilder.com/designing-immutable-concepts-with-transient-mutation-in-php/

Mark Ragazzo:
Immutable objects
May 04, 2016 @ 18:55:42

In a post to his site Mark Ragazzo looks at immutable objects - what they are and how they can be used in a PHP application with some "final" functionality.

In this short article we will see what immutable objects are and why we should consider to use them. Immutable object is an object that does not change its state after it was created. Immutable objects usually are very simple. You may already seen them as enum types or primitives like DateTimeImmutable.

Further in this article you will learn that making simple objects immutable may save significant amount of your time by making impossible to make certain types of mistakes.

He starts with a list of a few things to remember when implementing immutable objects (like using the "final" keyword) and problems that can come without them. He then gets into some examples, showing how to create immutable Address and Money objects and how to use them when you need to update/get values from the object. He also covers some common "accidental mutability" cases like leaking internal object references and inheritance problems.

tagged: immutable object introduction example mutability accidental tutorial

Link: https://ragazzo.github.io/immutability/oop/2016/05/03/immutability.html

Ibuildings Blog:
Programming Guidelines - Part 3: The Life and Death of Objects
Feb 02, 2016 @ 17:42:05

The Ibuildings blog has posted the latest part of their series looking at some general programming guidelines and principles that can help you in your own development work. In this latest article Matthias Noback talks about the "life and death of objects" in more detail including creating, updating and how they "die".

In the first part of this series we looked at ways to reduce the complexity of function bodies. The second part covered several strategies for reducing complexity even more, by getting rid of null in our code. In this article we'll zoom out a bit and look at how to properly organize the lifecycle of our objects, from creating them to changing them, letting them pass away and bringing them back from the dead.

He starts with a brief list of things that are true about objects (they live in memory, they hide implementation, etc) and some of the issues with poor object handling. He then gets into some of the basics: creating objects (meaningful & different ways), validating the input to constructors and methods and changing them to update properties and related objects. He also suggests preferring immutable objects and talks about value objects to help towards this goal. Finally he talks about the death of objects and some of the ways you can possibly "bring them back to life".

tagged: oop object detail introduction validate immutable valueobject revive lifecycle tutorial

Link: https://www.ibuildings.nl/blog/2016/02/programming-guidelines-part-3-the-life-and-death-objects

SitePoint PHP Blog:
Flyweight Design Pattern and Immutability: A Perfect Match
Oct 22, 2015 @ 16:56:32

The SitePoint PHP blog has a tutorial they've posted (from author Andrew Carter) looking at the Flyweight design pattern and immutability, how they're a "perfect match". The flyweight pattern makes it possible to reuse objects after they've been created with one requirement: they must be immutable.

The fundamental principle behind the flyweight pattern is that memory can be saved by remembering objects after they have been created. Then, if the same objects need to be used again, resources do not have to be wasted recreating them. [...] You can think of the flyweight pattern as a modification to a conventional object factory.

One important feature of flyweight objects is that they are immutable. This means that they cannot be changed once they have been constructed. This is because our factory can only guarantee that it has remembered the correct object if it can also guarantee that the object it originally created has not been modified.

The post includes code examples of how to implement the pattern with a simple File object that fetches data from a file when created. He then creates the factory class, with a getFile method that takes in the path and creates the immutable File object from it. It's then stored in an internal array for potential reuse later. He also talks about how the pattern could be useful for handling enumeration objects and how you can use it to build out "type" objects.

tagged: flyweight designpattern immutable object factory tutorial type enumeration

Link: http://www.sitepoint.com/flyweight-design-pattern-immutability-perfect-match/

Woody Gilk:
Immutable Data Structures in PHP
Sep 23, 2015 @ 16:48:34

Woody Gilk has posted an article to his site looking at immutable data structures in PHP and a library that's come from the research and work he did to implement them in PHP.

As someone who most often works with PHP I often find myself envious of the more advanced data structures that are present in a language like Python. As an experiment, I decided to see if it would be possible to bring some of those basic structures to PHP while also preserving immutability. The result of this experiment is Destrukt.

He starts off talking about immutable data structures and introducing some of the basic concepts and usage around them. He notes that they "cannot be modified by accident" and how, if they do need to be changed, they'd actually be reassigned not updated. He then talks about PHP arrays, how they're normally used in PHP and how their flexibility can lead to potential issues in the code. His library implements more strict versions of the same functionality in the form of dictionaries, orderedlists, unorderedlists and sets. He includes examples of using the library to create these objects and how to get the data back out of them for evaluation.

tagged: immutable data structure introduction destrukt dictionary orderedlist unorderedlist set

Link: http://shadowhand.me/immutable-data-structures-in-php/

Joe Fallon:
Immutable Objects in PHP
Aug 27, 2015 @ 16:53:36

Joe Fallon has a post to his site talking about immutable objects in PHP, objects that once the property values are set they cannot change.

When I first learned to program, I made many objects that were mutable. I made lots of getters and lots of setters. I could create objects using a constructor and mutate and morph the heck out of that object in all kinds of ways. Unfortunately, this led to many problems. My code was harder to test, it was harder to reason about, and my classes became chock full of checks to ensure that it was in a consistent state anytime anything changed.

[...] Now, I favor creating immutable objects. The folks over in the functional camp are super excited about this concept. However, it’s been around for quite a while and it has so many benefits.

He talks about how immutable objects make it easier to not only test code but also allow for more rational reasoning about their contents. He points out that they also make it easier to understand the state of an application should an exception arise. He then gets into some examples of immutable objects, creating an ImmutableClass and a ImmutableClassBuilder to help create instances based on values provided.

tagged: immutable object introduction class builder example benefits

Link: http://blog.joefallon.net/2015/08/immutable-objects-in-php/


Trending Topics: