Tag Archive for 'PHP beginners'

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

PHP OOP: Back to Basics

beginBack to Basics

Whenever I venture outside of PHP, which has become more regular as I’m working on app development in both iOS and Android. The former is Objective C and the latter, Java. Both languages are embedded in OOP and design patterns. It is during these ventures abroad (so to speak) that I’m reminded of some core issues in good OOP. I usually notice them when I realize that I’m not exactly paying attention to them myself.

Don’t Have the Constructor Function Do Any Real Work

When I first came across the admonition not to have the constructor function do any real work, I was reading Miško Hevery’s article on a testability flaw due to having the constructor doing real work. More recently, I was reviewing some materials in the second edition of Head First Java, where the user is encouraged to,

Quick! Get out of main!

For some Java and lots of C programmers “main” is the name for a constructor function, but I like PHP’s __construct() function as the preferred name since it is pretty self-describing. “Main” is a terrible name because the real main is in the program made up of interacting classes.

In both cases, the warning about minimizing the work of the constructor function is to focus on true object oriented applications where you need objects talking to one another. Think of this as a series of requests where a group of people are all cooperatively working together, each from a separate (encapsulated) cubicle, to accomplish a task. By having the constructor function do very little, you’re forcing yourself (as a programmer) to use collaborative classes. Play the example and download the code to get started:
PlayDownload

A General Model for PHP OOP

As a nice simple starting place for PHP OOP, I’ve borrowed from the ASP.NET/C# relationship. ASP.NET provides the forms and UI, and C# is the engine. As an OOP jump-off point, we can substitute HTML for ASP.NET and PHP for C#. The Client class is the “requester” class. The UI (HTML) sends a request to the Client, and the Client farms out the request to the appropriate class. Figure 2 shows this simple relationship.

Figure 1: A Simple OOP PHP Model

Figure 1: A Simple OOP PHP Model

If you stop and think about it, OOP is simply a way to divide up a request into different specializations.

Avoid Conditional Statements if Possible

Figure 2: Requests begins with a UI built in HTML

Figure 2: Requests begins with a UI built in HTML

If you avoid conditional statements, and this includes switch statements, I think you can become a lot better programmer. In the example I built for this post, the user chooses from two different types of requests (classes), and each request has a refined request (method) that provides either of two different kinds of math calculations or display options. Figure 2 shows the UI (HTML) for the example. If the user selects “Do a Calculation” it sends the request to the Calculate class, but if the user selects “Display a story”, the request is handled by the Display class. Further, not only must the right class be selected, the right method in that class must be selected as well. The obvious answer is to get information from the UI and using a switch or set of conditional statements work out in the Client how to handle each request. You could even use (shudder) nested conditional statements. That approach could work, but when you start piling up conditional statements, you’re more likely to introduce errors, and when you make changes, you’re even more likely to make errors. The only good thing about conditionals is that you don’t have to tax your brain to use them.

Suppose for a second that all of your conditional statements were taken away. How, using the information sent from the HTML UI to the Client class can the selections be made without conditional statements? (Think about this for a moment.)

Think, pensez, pense, думайте, piense, 생각하십시오, denken Sie, 考えなさい, pensi, 认为, σκεφτείτε, , denk

Like all things that seem complex, the solution is pretty simple. (Aren’t they all once you know the answer.) Both classes were given the value of their class name in their respective radio button input tags. Likewise, the methods were given the value of their method names. With two radio button sets (request and method), only two values would be passed to the Client class. So all the Client had to do was to use the request string as a class name to instantiate an instance of the class, and employ the following built-in function:

call_user_func(array(object, method));

That generates a request like the following:

$myObject->myMethod;

In other words, it acts just like any other request for a class method. By coordinating the Client with the HTML UI, that was possible without using a single conditional statement. In this next section, we’ll now look at the code.
Continue reading ‘PHP OOP: Back to Basics’

Share

Easy Writer: Setup for Raspberry Pi PHP

RaspPHPFocus on writing PHP Code

In fiddling around with PHP on a Raspberry Pi running on a Debian Linux OS more or less directly from a terminal mode, I realized that the focus (in my case) was getting the Linux commands right and very little with actually writing PHP programs. Most queries about getting the setup right involved Linux system administration and not PHP programming.

This short post is for Raspberry Pi users (and perhaps Linux users in general), and it focuses on setting up your Raspberry Pi so that you can use default Raspberry Pi editors (LeafPad) and the File Manager to work with PHP programs. Once set up, you will find the process of creating server-side programs in PHP much easier with no need to use the  terminal editors after setting up your system.

Installing Apache and PHP

Because PHP is a server-side language, you will need both a server and PHP installed on your Raspberry Pi. Using the Root Terminal (Accessories → Root Terminal), enter the following line:

sudo apt-get install apache2 php5 libapache2-mod-php5

Press the Enter key and patiently wait until it’s completed the setup. Once done, you computer will have both a web server and PHP installed. To test whether installation was successful, open a browser from the main menu (Internet → NetSurf Web Browser) and enter the following:

  http://localhost/

If everything works, you will see the message shown in Figure 1 on the right:

Figure 1: Default Web Page

Figure 1: Default Web Page

This location (http://localhost) is the root for your Web pages—PHP and any other Web page you decide to put on your Raspberry Pi Apache server. The name of the file is index.html. On your Raspberry Pi, in the Linux file system, the address is:

  /var/www/

Open the File Manager (Accessories → File Manager) and in the window where you see /home/pi enter /var/www. You will now be able to see the icon for the html file that was automatically created when you installed the Apache server.
Continue reading ‘Easy Writer: Setup for Raspberry Pi PHP’

Share

OOP PHP II: Arithmetic Operators and Communicating Objects

oop2Object Communication

Hope to get up the final CMS post by tomorrow (July 9), but in the meantime, I wanted to get this next OOP PHP post up. One of the essential elements of OOP in any language is that it is written as communication between objects. Design patterns are simply ways to help arrange that communication process so that things don’t get tangled up. Sequential and procedural programming are never far from the abyss of tangle, and as long as the scripts or code blocks are short, you can get away with it. But for both the sequential and procedural programmers, spaghetti code is lurking like a vulture on the programmer’s shoulder. So in learning OOP, one of the very first things to understand and use is how objects communicate with one another.

In learning PHP or any other language, one of the first things to understand is how to use the arithmetic operators. The six such operators in PHP are – (negation) + (add), – subtract, * (multiply), / (divide) and % (modulus). Usually the next step is to learn about precedence and how to use parentheses to re-order precedence. However, other than a quick mention that modulus refers to finding the remainder in division, there’s usually not a lot of discussion about it. However, for programmers there’s a huge number of uses of modulus. Check out some articles on modular arithmetic. (You’ll never have problems working with 12-hour clocks again using $value % 12.)

Some examples

I put together some simple code examples of using object communication and math operators. It might help to have them handy when viewing the video. Each listing below should be saved as a separate file with the .php extension.

Call to single method object

Client.php

<?php
//Client.php
ini_set("display_errors","1");
ERROR_REPORTING( E_ALL | E_STRICT );
include_once('EZMath.php');
 
class Client
{
    public function __construct()
    {
       $math = new EZMath();
       echo $math->doAdd(7, 22);    
    }  
}
$worker = new Client();
?>

EZMath.php

<?php
//EZMath.php
ini_set("display_errors","1");
ERROR_REPORTING( E_ALL | E_STRICT );
 
class EZMath
{ 
   public function doAdd($alpha,$beta)
   {
        return $alpha + $beta;
   }  
}
?>

Call to multiple method object

Client1.php

<?php
//Client1.php
ini_set("display_errors","1");
ERROR_REPORTING( E_ALL | E_STRICT );
include_once('EZMath1.php');
 
class Client1
{
    public function __construct()
    {
       $cr = "<br />";
       //Enter your own birth year
       $bday = 1985;
 
       $math = new EZMath1();
       echo $math->doNegate(44) . $cr;
       echo $math->doAdd(12, 26) . $cr;
       echo $math->doSubtract(2013, $bday) . " years old $cr";
       echo $math->doMultiply(12, 26) . $cr;
       echo $math->doDivide(500, 25) . $cr;
       echo $math->doModulus(14, 12) . " pm o'clock $cr";  
    }
 
}
 
$worker = new Client1();
 
?>

EZMath1.php

<?php
//EZMath1.php
ini_set("display_errors","1");
ERROR_REPORTING( E_ALL | E_STRICT );
 
class EZMath1
{
 
   public function doNegate($alpha)
   {
        $alpha = -$alpha;
        return $alpha;
   }
 
   public function doAdd($alpha,$beta)
   {
        return $alpha + $beta;
   }
 
   public function doSubtract($alpha,$beta)
   {
        return $alpha - $beta;
   }
 
   public function doMultiply($alpha,$beta)
   {
        return $alpha * $beta;
   }
 
   public function doDivide($alpha,$beta)
   {
        return $alpha / $beta;
   }
 
   public function doModulus($alpha,$beta)
   {
        return $alpha % $beta;
   }
}
 
?>

Coin Flip Game Using Modular Arithmetic

CoinClient.php

<?php
//CoinClient.php
ini_set("display_errors","1");
ERROR_REPORTING( E_ALL | E_STRICT );
include_once('CoinFlip.php');
 
class CoinClient
{
    public function __construct()
    {
       //Instantiates instance
       $flipper = new CoinFlip();
       //Makes a request
       echo $flipper->doFlip();   
    }   
}
$worker = new CoinClient();
?>

CoinFlip.php

<?php
//CoinFlip.php
class CoinFlip
{
   public function doFlip()
   {
    //rand is built-in PHP method for generating random number
    $coin = rand(1,200);
    //Uses modulo operator (%) to generate 1 or 0
    //When you divide by 2 the remainder is always 1 or 0
    //tests for true (1) or false (0)
    $results = $coin % 2;
    if($results)
    {
        $flip="Heads";
    }
    else
    {
        $flip = "Tails";   
    }
    return $flip;
   }
}
 
?>

You can play around with these examples, and you should get the fundamental idea of objects communicating with one another. See if you can create some of your own.

Share

PHP OOP: An Introduction to Rocket Science

classWe All Have to Start Somewhere

Rather than assume any given level of experience with OOP, I am going to start with some simple OOP principles. I’ve made videos of the materials in this post: 1) Creating a class and 2) Calling a class. I’m working on adding a video page to the Sandlight page, but for now you can see the videos in the Youtube site.

Object Oriented Programming (OOP) is for organizing your thinking about programming. It will not make your programs run faster, but if you’ve developed algorithms to help speed up your PHP programs, you can use the same algorithms in OOP. You can see the main value of OOP when your begin developing larger programs. A good understanding of OOP will help you program faster, repair and/or change programs faster. In the very real world where developers are paid to develop programs in PHP, clients want you to make changes, and as your program grows, making changes is more difficult. OOP and Design Patterns will save your life in these situations.

Objects

The first thing to understand is that programs are developed in modules rather than in long single programs stored in a single file. If you hear someone brag about a 3,000 line program, let’s hope those 3,000 lines are organized into several classes that encapsulate different tasks. Then, let’s hope that when Elmo changes one line of code, the whole thing doesn’t come crashing down on his head.

So how do we make objects? In PHP (and other languages), you begin with a class. Generally, when you create a class, you put together an object that does one thing. For example, the following class does one thing: It prints out “Hello World.” (Save the following class as class1.php)

< ?php
class FirstClass
{
	private $prop;
	public function firstMeth()
	{
		$this->prop="Hello World";
		echo $this->prop;
	}
}
?>

It’s made up of a property ($prop) and a method (firstMeth()). In general, a property is a characteristic of the object (like a person has brown eyes), and the method is something that the object does (like a person writes programs.) This class has a property with a value of “Hello World” and a method that prints out the contents of the property. Don’t worry about what private and public mean; we’ll get to those in another post. (Click to learn how objects communicate!)
Continue reading ‘PHP OOP: An Introduction to Rocket Science’

Share