Tag Archive for 'oop beginners'

PHP Recursion: The Fundamentals

recursionNailing Down Recursion

On more than one occasion on this blog, I’ve wandered off into the land of operations to examine recursion. In looking over past recursion posts and recursion discussions on the Web, I found a lot of bad information, partial information and helpful information. Likewise, I consulted some programming books, especially Robert Sedgewick’s and Kevin Wayne’s 2011 edition (4th) of Algorithms. Also, I found a great and detailed article on recursion by David Matuszek. Robert Sedgewick and Kevin Wayne are professors at Princeton and David Matuszek is a professor at the University of Pennsylvania. Not surprisingly, their focus is on larger conceptual and mathematical issues surrounding computer programming and the role that recursion plays in that context.

However, I also wanted to get a non-academic view from developers, and I found two very good posts on Martin Fowler’s Refactoring site by Dave Whipp and Ivan Mitrovic. For those of you not familiar with Martin Fowler, he’s written books and articles on computing and is one of the founders of the Agile Movement in program development. He is a primary consultant to businesses and institutions who want to optimize their programs for efficiency and effectiveness. Among PHP developers the Agile approach to programming is quite popular.

What is Recursion?

In a nutshell,

Recursion in computer programming occurs when a method calls itself.

While that definition is a starting point, a more detailed and useful one is provided by Sedewick and Wayne. They spell out three features in a good recursive method:

  1. A recursion begins with a conditional statement with a return. This is called the base case (or halting case), and it supplies the criterion which will stop the recursive operation.
  2. Recursive calls to sub-problems converge to the base case. Each call must bring the values in use closer to the halting conditions.
  3. Called sub-problems should not overlap.

You can find a lot of discussions and debate about the definition and use of recursive methods in programming, but the fundamental fact remains that recursion is one of the central ideas in computer science. As a professional programmer, you need to know about recursion and you should use it. This does not mean you have to use it all the time, but you need to understand what you can do with it and its limitations and advantages. Start off with the following implementations and download the code:
PlayDownload

In PHP and other computer programs, recursion and the need for it arise all the time. So you should have some sense of how to use it and when. Like other computing concepts, you may not use it all the time, but when you need it, you really need it.

World’s Easiest Recursive Function

To get started we’ll look at a simple recursive call. It is a version of what kids do when you take them on a trip. (And what you did when you were a kid on a trip…) You’d ask the reasonable question,

Are we there yet?

If you kept calling the same query as soon as you’d received a negative response, it has recursive-like qualities. The “No!” is the base case, and the car moving to the objective (“there”) is the change that occurs between each call to the query, “Are we there yet?”

//Recursion.php
< ?php
class Recursion
{
    private $ask="<span style='font-family:sans-serif;'>Are we there yet?<br />";
    private $answer="No!<br />";
    private $counter=0;
    public function __construct()
    {
        $this->thereYet();
    }
    private function thereYet()
    {
        //Base case (also called 'halting case')
        if($this->counter < =10)
        {
            echo $this->ask;
            echo $this->answer;
            $this->counter++;
            //Recursive call
            return $this->thereYet();
        }
        else
        {
            echo "<p></p>" . $this->ask;
            $this->answer="<strong><em>Yes! We are there!</em></strong>" ;
            echo $this->answer;
        }
    } 
}
?>

The return value calls for a recursive event inside the thereYet() method. With each call, the counter variable’s value moves toward convergence with the base case. After 10 calls, the counter variable exceeds the base case and no more self-calls are made by the thereYet() method.

While that example could be handled by iteration in a loop; it provides another way to accomplish a task. It’s easy to understand and meets the criteria set up for recursion. (Click below to see more.)
Continue reading ‘PHP Recursion: The Fundamentals’

Share

PHP OOP: Encapsulating & Communicating with JavaScript and HTML5

EncapDocCan We Talk?

The initial discussion of the Memento design pattern illustrated how a state could be saved in a different object than the one in which the state originated. A Caretaker object holds the saved state and when requested, it returns the state to the Originator, all without breaking encapsulation. A practical example of employing the Memento that comes to mind is where the user is looking through a list. As she goes through the list, she sees different items (flowers in this case) that she is considering. However, because it’s a long list, she cannot remember which one she likes; so she tags those she is considering. After going through the whole list (all of the different flowers), she can easily recall those that she had tagged–recall them from a Memento. Play the little app and download the source code before going further:
PlayDownload

Communicating with HTML and JavaScript

Working HTML and JavaScript into PHP is no great shakes, and most PHP developers probably have done so at one time or another. However, most of the time I find myself creating horrible mixes of code for a one-off use with nothing encapsulated. The goal here is to see how everything in the application can be encapsulated and at the same time communicate. The purpose here is to find a single state variable that is used by HTML, JavaScript and PHP. Further, that state must be available for placing into a Memento object and stored for later use. (This post simply examines one way to encapsulate everything and have them communicate; however, material from this post will be used in developing a Memento example in a future post.) Also, I wanted to import all of the JavaScript and CSS separately. Figure 1 shows the general plan. (The ‘gardner’ folder contains the flower JPEG images.)

Figure 1: Encapsulating JavaScript, CSS and HTML into EncapDoc PHP class

Figure 1: Encapsulating JavaScript, CSS and HTML into EncapDoc PHP class

The CSS is just the stylesheet and it contained no functionality that you often find when it is used in conjunction with jQuery. I needed the JavaScript for clicking through the images. Had I swapped images using PHP I’d probably have to reload an HTML page with every swap and that seem prohibitively expensive. So I wrote the most simple JavaScript swap program I could think of with two functions for swapping and an added JavaScript function to get the initial starting picture (an integer value) passed from PHP. The following JavaScript listings shows how simple the script is:
Continue reading ‘PHP OOP: Encapsulating & Communicating with JavaScript and HTML5’

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

PHP Game Coding: SVG Movement

flashEncapsulating Movement

Any sane person would abandon PHP for JavaScript, Ajax, jQuery or some other client-side language that would work directly with Web-based SVG graphic elements and attributes. In doing so, though, it would give up on both the OOP capacity of PHP (lacking in these other languages) and low cost (no open socket server) inter-internet games (i.e., remote multiplayer games.)

Ironically (for some), the easiest part of creating action games is the game physics. You just need to take a formula from physics (e.g., deceleration, acceleration) and turn it into an algorithm. Eventually, we’ll get to that luxury, but first we need to work out the mechanics of changing the position of a SVG graphic on a grid. Before getting into that discussion, click the Play button to see the end results (goal) and the Download button to see the code:
PlayDownload

As you will see, there’s not a lot to play with, but it does deal with two velocity issues; velocity itself and capacity. It’s like comparing the velocity of a 2014 Rolls-Royce Wraith with that of a 1988 Trabant 601. Both cars can attain speeds of 100 km/hr (62 mph), but the Wraith can do it much faster and go far above that speed because it has a more powerful engine. It has greater capacity.

The Space Grid

In the previous post on using SVG graphics in making games, you can see the grid setup, and in that grid you can determine distance and collision using simple geometry. If you’ve spend any time with SVG graphics, you will find a animation system to move graphics along paths. The problem with that system (for now at least) is working out position and collision detection. Movement along paths has grid-like parameters in defining X and Y locations on a grid, but paths can also be defined in terms of curves, and knowing the position of an object at any given time can be problematic. Further, movement is a function of timing using the SVG animateMotion element. For example, consider the following path:

    animateMotion fill=”freeze” path=”M 0 0 L 100 150″ dur=”.5s”

It moves an SVG object from 0,0 to 100,150 in a half a second (0.5 seconds). There is no checking along the way for collision. Using a Bézier curve the following movement goes from 0,0 to 300,0 in two seconds (2s) but it curves downward before reaching its destination.

    animateMotion fill=”freeze” path=”M 0 0 T 100 150 T 300 0″ dur=”2s”

Again, what it may have collided with is unknown given both the timing of the motion and the curve. This is not to say that every point could not somehow be tracked, but at this point I’d rather take a more familiar route to movement and collision detection.

Moving SVG objects involves changing their X and Y values. I’m calling the frequency with which the X and Y values are updated, “capacity” and the amount of change “velocity.” Rather than using the animateMotion SVG element, this example changes the object’s X value through timed updates and variable values in the number of pixels each timed update generates. For example, an update of every 50 milliseconds is faster than one of every 100 milliseconds—there’s less time between each update pause. Likewise, an X increment of 10 pixels will cause faster movement than an update of 5 pixels.

A timed loop fires a function that changes the ship’s position:

?View Code JAVASCRIPT
function moveShip()
{
     // Change the ship's position
     shipX += $this->velocity;
     shipX = shipX % 500;
     oopz.setAttribute("x", shipX);
}

As you can see the code is JavaScript using a PHP variable ($this->velocity) to set the speed. I would have preferred to do it using all PHP, but needed to use the JavaScript setAttribute method for moving the ship’s X position without having to create a new object. Changing the speed using capacity (loop timing) and velocity (amount of variable increment) requires PHP to create another SVG object, and for demonstration purposes, that’s fine. In an action game, though, it’d eat up a lot of resources.

The “ship” (rectangle) only moves from left to right at this time, and when it leaves “the galaxy” it loops around and comes in the other end. Using the modulus of 500 (% 500), the value will always be calculated correctly when moving from left to right (in both JavaScript and PHP); however, moving from right to left, as soon as the X position is 0, it fails. (See this post on game algorithms for a detailed explanation and comparison of how the modulus operator works differently in Python than PHP and JavaScript). It’s an easy fix using conditional statements, but that’s so…I don’t know…inelegant? See what you can do. For now, continue on to see how the Move class is created and used.
Continue reading ‘PHP Game Coding: SVG Movement’

Share

The Composite Design Pattern in PHP: Part II Composing with Images

cornerDon’t forget to Program to the Interface!

While the primary principle we draw from the Composite pattern is , Favor object composition over class inheritance, as discussed in Part I of the Composite series, another important principle applies here as well. The very first principle of design patterns is, Program to an interface, not an implementation. In a sense this is saying, program to an abstract parent and not a concrete child, but if you understand an interface to be the structure implied in either an interface (as used in the first and in this example) or an abstract class, you can see what the value of that principle is.

In this part, instead of a single leaf and a hierarchy rending output, this example shows how a Composite design with multiple leaves can be used to create a mosaic—which is the essence of composite! The interface (IComponent) is little changed except the string parameter has been removed from the operation() method and replaced (for clarity) with a method named showPix() with no parameters. All of the other methods remain the same. Play the application and download the source code and files to get started:
PlayDownload

Follow the Structure; Not the Sequence

To get out of the tar pit of sequential programming, look at the structure and think in terms of using larger structural concepts. Take a look at the three key participants in the Composite pattern, beginning with the key structural participant, the IComponent interface, focusing on their structure as outlined in the interface.

<?php
//IComponent.php
interface IComponent
{
    public function showPix();
    public function add(IComponent $comOn);
    public function remove(IComponent $comGone);
    public function getChild($someInt);
}
?>

As in Part I, the IComponent has four methods to be implemented, and though all four are implemented, only the first two are used for this second part. The focus is still on the idea of composition. The fact that we don’t need the second two right now does not detract from the fact that they (remove() and getChild() methods) unimportant for the pattern; just not for this example.

So the implementation of the the Composite class looks structurally similar to that in Part I, but the constructor function has no node name to identify in a parameter. Likewise, the showPix() method is almost identical to the operation() method in Part I, and only the name of the array has changed from $aChildren to $mosaic. Also, the echo statement is no longer part of the method.

<?php
//Composite.php
class Composite implements IComponent
{
    private $mosaic;
 
    public function __construct()
    { 
        $this->mosaic=array();
    }
 
    public function add(IComponent $comOn)
    {
        array_push($this->mosaic,$comOn);
    }
 
    public function remove(IComponent $comGone)
    {
        //Code to remove component
    }
 
    public function getChild($someInt)
    {
        //Code to get child by element value
    }
 
    //Note: The following method is recursive
    public function showPix()
    {
        foreach($this->mosaic as $tile)
        {
            $tile->showPix();
        }
    }
}
?>

If you’ve played both Part I and Part II examples of Composite patterns, you know they are very different in what they generate, but the structures for both are virtually identical. Each is combining leaf elements into composite ones. Same structure; different outcomes. That virtually defines code re-use.

Parts is Parts

While the implementation of the Composite class is little unchanged, the number and implementation of the leaf nodes are different. Each leaf class has a single task and no constructor parameter. The unused methods are implemented the same. Each leaf contains an HTML tag to an image. The Composite class stores instances of leaf instances in the $mosaic array and creates rows of images that are aligned to display the tiled image. You can think of each tile in the display as a leaf, and each row a composite of tiles and the entire mosaic as a composite of the three composites that make up the rows.

<?php
class Leafr1c1 implements IComponent
{   
    /* None of this batch of methods are used by leaf participants */
    /* However in order to correctly implement the interface */
    /* you need some kind of implementation */
    public function add(IComponent $comOn){}
    public function remove(IComponent $comGone){}
    public function getChild($someInt){}
 
    /* Display tile */
    public function showPix()
    {
        echo "<img src='images/r1c1.png' alt='r1c1'>";
    }
}
?>

Each of the leaf classes is named after a column and row where the tile is to be placed. For example the leaf class to place an image in Row 2, Column 3 of the mosaic is named Leafr2c3. Likewise, the names of the PNG graphic files share the same naming conviction. So Leafr2c3 has the code to display the r2c3.png image file.

The Client

As an integral part of the Composite design pattern, the Client can be seen as the artist who composes the mosaic. He does this by selecting each tile for the rows and arranges them to get the desired picture. Because no string parameter is in the leaf constructors, each leaf added to a composition does not need a name. (In a sense, the title names have been embedded into the leaf names.) The $bigPictue property is the same name as used in the original Client example, except this time, it really will produce a “big picture.” It is the root composition made up of three row compositions that are made up of three leaf elements.

<?php
ERROR_REPORTING( E_ALL | E_STRICT );
ini_set("display_errors", 1);
function __autoload($class_name) 
{
    include $class_name . '.php';
}
class Client
{
    private $bigPicture;
 
    public function __construct()
    {
        $this->bigPicture = new Composite();
        $row1=new Composite();
        $row1->add(new Leafr1c1());
        $row1->add(new Leafr1c2());
        $row1->add(new Leafr1c3());
        $this->bigPicture->add($row1);
 
        $row2=new Composite();
        $row2->add(new Leafr2c1());
        $row2->add(new Leafr2c2());
        $row2->add(new Leafr2c3());
        $this->bigPicture->add($row2);
 
        $row3=new Composite();
        $row3->add(new Leafr3c1());
        $row3->add(new Leafr3c2());
        $row3->add(new Leafr3c3());
        $this->bigPicture->add($row3);
 
        //Create a compostion
        echo "<!doctype html><html><head>";
        echo "<link rel='stylesheet' href='india.css'>";
        echo "<meta charset='UTF-8'></head><body>";
        echo "<h1>Leaders in Composition</h1>";
        echo "<header>India</header>";
 
        $this->bigPicture->showPix();
 
        echo "<figcaption>Mahatma Gandhi</figcaption>";
        echo "</body></html>";
    }
}
$worker=new Client();
?>

In this installment, the goal is to show that the Composite design pattern is more than a tree-like hierarchy-making pattern. It is the essence of composition and the Composite design pattern. The mosaic image is a metaphor for the pattern in that it is composed of several compositions and elements within those compositions.

Adding the Final Touches

With two unimplemented methods (remove() and getChild()), in Part III of this series, you will see how they can be used for added flexibility with the Composite design pattern. I’d like to look at the original Gang of Four idea of using the Composite pattern to create a drawing program. Until next time, I welcome any and all comments.

Share