PHP Functional Programming Part II: OOP & Immutable Objects

immutableImmutable

In his book on Functional Programming in PHP Simon Holywell laments the lack of immutable structures in PHP, and while he suggests some hacks to insure immutability, we can make-do with some different hacks I’ll suggest. (Most of the hacks are mind-hacks–a way of thinking about data.) The idea of having a programming language where all objects are immutable (unchanging) sounds pretty awful. Not only that, it sounds impractical. Take, for example, a Boolean. It has two states; true and false. In functional programming, that means the Boolean variable is mutable, and so it’s out. However, you can have two objects that we can call, Alpha and `Alpha. Alpha is true and `Alpha is false. (The tick mark [`] is the key below the ‘esc’ key on your keyboard.) So instead of changing the state of Alpha from true to false, you change the object from Alpha to `Alpha.

Why would anyone want to do that? It has to do with the concept of referential transparency. In a concrete sense it means that if an object (reference) were replaced by its value, it would not affect the program. Consider the following:

   $val=5;
   $alpha= function() use ($val) {return $val * $val;};

can be replaced by;

   $alpha=25;

Nothing in the program will change if either $alpha variable is used. For a simple example of referential transparency, that’s no great shakes. Besides we lose the value of changing states. However, functional programming eschews the concept of changing states. To quote one functional programmer,

Do not try to change the state; that’s impossible. Instead only try to realize the truth: There is no state.

Again, this looks nuts both conceptually and in the real world. Take, for instance, a thermometer that changes from freezing (32F / 0C) to not freezing (say 50F / 10C). The temperature has changed states! How can anyone say it has not? Or a child changes states into an adult, or a caterpillar changes states to a butterfly?

According to the functional programming model, a freezing temperature is a different object than a non-freezing one; an adult is a different object than a child, and (clearly) a butterfly is a different object than a caterpillar. So, if I say that the thermometer has changed from 32° to 33°, it is not state that has changed, it is a different object. Objects can be as granular as you like, and if you think of atoms arranged to display a ruler, you can move from one atom (object) to the next atom (object) with no state involved at all.

The State Design Pattern: Wasn’t it Immutable All Along?

The State design pattern would seem to be the polar opposite of functional programming. However, if we examine it closely, we can re-conceptualize it as object swapping. Take a simple two-state example: a light going on and off. There’s a light-on object and a light-off object. The design is the same, but we think about it in different ways. Also, the individual state methods can include nothing but lambda functions or closures. Consider Figure 1. An “on” light JPG and an “off” light JPG can be considered two separate states or two immutable objects.

Figure 1: Two States or Two Immutable Objects

Figure 1: Two States or Two Immutable Objects

To make the State pattern more “immutable-like” the interface has two constants with the URLs for the two different images. To get started, Play the light switch State application and Download the files:
PlayDownload

The application uses a simple State design pattern. All requests go through the Context, which keeps track of the current state. However, this implementation fudged a bit because each time the UI calls the Client, it creates a new Context object; so no state is saved, and I had to add a statement to use the called method to set the correct state for switching the light on and off. (Note to self: Get busy on the RESTful API!) Also, I added two constants to the interface (IState) to impose an immutable property in the state implementations. Figure 2 shows the class diagram of the implementation:

Figure 2: State design pattern implementation

Figure 2: State design pattern implementation

The pattern diagram in Figure 2 provides an overview of the classes and key methods in those classes. The LightSwitch class is just an HTML document wrapped in a PHP class, an it is where a request originates in this model. The other roles you can see in the following outline:

  • Client: Get the request from the UI (LightSwitch) and using a Context instance and method, the request is sent to the Context.
  • Context: Always the most important participant in a State design pattern, it determines the current state and passes the request to it via the appropriate method based on the request.
  • IState: The State interface specifies the required methods and may include constants.
  • Concrete States: The On / Off states (IState implementations) return the requested state-as-an-object.

With that overview in mind, you can better understand all of the singular roles of the participants. (Continue to see listings and explanations.)
Continue reading ‘PHP Functional Programming Part II: OOP & Immutable Objects’

Share

PHP Functional Programming Part I: An Introduction

functionThe Functional Alternative

For some time now, I’ve been interested in functional programming. I had heard that it was an alternative to imperative programming (OOP languages, including PHP, are considered imperative languages) and if you sniff around you can find snarky comments by functional programmers about OOP. For the most part, though, the concern and need for functional programming has centered around multi-threaded and multi-core programming. If you can imagine two different threads using two different cores in your computer working in parallel to process a single giant list or array, you can understand how useful it is to divide the array in half and have different threads process each half. Since about 2005, all computers (except Raspberry-Pi types) are multi-core. Even my old iPhone 4S has a dual core A5 processor. With multi-threaded and parallel programming, though, you have to rejoin the multiple threads once each is finished to get a final result. Here’s where you have to be careful because you want to be sure that the values you’re handling have not changed in one thread and not the other or differently in both threads. You want to use immutable values to avoid surprises when the threads’ results are re-joined.

Where to Start?

A good starting point is Functional Programming in PHP by Simon Holywell. It’s about as simple as a book on functional programming can be, and you’ll find lots of examples. If you’re looking for material on lambda (λ) calculus and functional programming in PHP, you’ll only get a chapter that is ¾ of a single page, but Holywell goes on to say in the ever-so-brief chapter (chapter-ette?) on PHP lambdas,

…but just about every piece of functional code ever written makes use of lambda functions, and they are an important building block to add to your tool kit and should be mastered ….

Not to overstate a point, but Holywell is absolutely right, and so the reader is left wondering, why so brief a discussion of lambdas–a chapter that’s only three-quarters of a page? Well, the rest of the book has lots of lambda functions in use, and I imagine that the author figured the reader would be able to work it out on his/her own. (Maybe this point might be re-thought in the next edition of the book and the chapter be expanded.) In the meantime a useful online source can be found at Lambdas in PHP on the phpbuilder site.

If you really want to go nuts on functional programming, you can learn Haskell. On October 14, 2014 (in a couple weeks!) edX (the Harvard/MIT initiated free online course program) is offering Introduction to Functional Programming through The Netherland’s premiere technical university, Delft University of Technology. In the past I’ve learned that whenever I learn another programming language, I can always bring something back to PHP. Besides, the course introduction notes that PHP is one of the languages that has incorporated functional programming structures into its lexicon. You can take the course for free or get a certification for about $50. It’s 6 weeks long and will take between 6-8 hours a week of study.

For a quick and dirty differentiation between imperative programming and declarative (functional) programming, Microsoft has a nice little anonymous table that summarizes the difference. Being Microsoft, they put in a plug for their products and point out that C# can handle both functional and imperative programming. Since PHP 5.3, PHP too handles both types of programming; so we’re not dealing with an either or situation when it comes to OOP and functional programming in languages like PHP and C#.

So What Are Lambdas?

Lambda functions are anonymous functions, introduced in PHP 5.3.0. Essentially, a lambda function is one that stores an immutable value in a variable. For example,the following class has incorporated a lambda function to calculate the square of a value as part of the method doLambda().

< ?php
class Lambda1
{ 
   function doLambda()
   {
        $lambda_func = function($stuff) { return $stuff * $stuff; };
        echo "The square value is: " . $lambda_func(8) . "<p />";
   }
}
$worker=new Lambda1();
$worker->doLambda();
//Results - The square value is: 64
?>

To call a lambda function an anonymous function is true, but to assume that all anonymous functions are lambda expressions criminally oversimplifies the lambda calculus behind lambda expressions. To help move on in understanding of PHP lambda expressions stated as anonymous functions, take a look at Figure 1.

Figure 1: Elements of a lambda expression

Figure 1: Elements of a lambda expression

The parts of a lambda function are pretty straightforward, and you have to remember to add the semi-colon (;) after the lambda body in addition to the one at the end of expressions within the lambda body. Otherwise, it looks pretty much like a named function without the name.

Essential is the requirement to include the return statement in the lambda expression. In fact, it’s probably a better programming practice to use a return statement with all methods; a practice I’ve often overlooked myself. (See No Side Effects below.)
Continue reading ‘PHP Functional Programming Part I: An Introduction’

Share

PHP Introduction to OOP: UI-Client-Request

clientBasicAn Easy Start

A lot of starting concepts in OOP seem designed to confuse and warn off developers who want to move up to OOP from sequential and procedural programming. This post is to give you a bit of what was presented at the NE PHP & UX Conference and to provide a simple yet clear introduction to OOP applied to PHP.

The easiest way (and least confusing) is to begin with the idea of “objects” and communication between objects. As you may know, objects are made up of classes containing “properties” and “methods.” Properties look a lot like PHP variables and methods like functions. So, think of properties as things a car has–like headlights, a steering wheel and bumpers, and think of actions your car can take, like turning left and right or going forward and reverse as methods.

The “blueprint” for an object is a class, and when a class is instantiated in a variable, it becomes an object. Objects communicate with one another by access to public properties and methods.

At the 2014 NE PHP & UX Conference in Boston, I told those at my session that I’d have some materials for them, and so you can download them here. One is a folder full of examples from my session and the other is an introductory book (in draft form) for getting started in OOP for PHP users. Also, the Play buttons runs the little example program for this post.
PlayconfFilesoopBook

A Request-Fulfill Model

At the heart of OOP is some system of communication. The simplest way to think about communication between objects is a request-fulfill model. A client makes a request to an object to get something. The request can originate in the user UI, and it is passed to a client who finds the correct class and method to fulfill the request. Figure 1 shows a file diagram with an overview of this model:

Figure 1: Object communication

Figure 1: Object communication

In Figure 1, you can see that the only non-object is the CSS file (request.css), and so in a way, you’re used to making requests for an external operation if you’ve used CSS files. However, CSS files are not objects but rather depositories. Likewise, external JavaScript (.js) files can be called from HTML documents for use with Web pages, but they too are not objects.

Encapsulating HTML in a Class

With PHP, the UI is handled by HTML, but that does not mean that it cannot be encapsulated in a PHP object. Encapsulation is not accomplished by simply adding a .php extension to the file name, but rather, fully wrapping the HTML in a PHP class. The easiest way to do that is with a heredoc string. The following example shows how a fully formed HTML5 document is encapsulated:

Listing #1:

< ?php
class RequestUI
{
    private $ui;
 
    public function request()
    {
        //Heredoc wrapper
        $this->ui=< <<UI
        <!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" type="text/css" href="request.css"/>
    <title>Request</title>
</head>
 
<body>
    <h3>Mathster Mind:<br /> The UI Class & Method Requester</h3>
<form name='require' action='Client.php' method='post' target='feedback'>
    <input type='hidden' name='class' value='MathsterMind'/>&nbsp;MathsterMind Class<br />
    <input type='text' name='num' size='6'/>&nbsp;Enter value <br />
 
    <fieldset>
        <legend>Methods</legend>
    <input type='radio' name='method' value='doSquare'/>&nbsp;Square the value<br />
    <input type='radio' name='method' value='doSquareRoot'/>&nbsp;Find the squareroot of the value<br />
    </fieldset><br />
    <input type='submit' name='send' value='Make Request'/>  
</form>
<iframe name='feedback'>Feedback</iframe>
 
</body>
</html>
UI;
    echo $this->ui;
    }  
}
//Instantiate an object from the class
$worker=new RequestUI;
//Call the public method from the instantiated object
$worker->request();
?>

The key aspect of encapsulating HTML in a class is the heredoc wrapper:

//Heredoc wrapper
$this->ui=<<<UI
//HTML Code
UI;

A heredoc string begins with three less-than symbols (they look like chevrons laid on their side), the name you give the heredoc string and it ends with heredoc string name fully on the left side of the source code and terminated with a semi-colon. Typically, the heredoc string is assigned to a variable ($this->ui). The great thing about using heredoc, is that you can develop and debug your HTML document, and once it’s all ready, you just paste it into a heredoc wrapper. Now, instead of a free range chicken running around with snippets of PHP code, you have a fully encapsulated object. Thus, your UI is a PHP class with all of the possibilities and security of a well formed class. (Click below to see how requests are “caught” by a PHP client.)
Continue reading ‘PHP Introduction to OOP: UI-Client-Request’

Share