Archive for the 'Beginning PHP OOP' Category

Bulgaria PHP Group: Introduction to Design Patterns

freedomIntroduction to Design Patterns. On Saturday, February 13 from 4:30-??? EST (New York time and 10:00-13:00 EET UTC 9:00-12:00) I will be making a presentation to the Bulgarian PHP Group via Google Hangouts. If you are unfamiliar with PHP 7, click on the picture of Vasil Levski, and download the special Bulgarian Edition! of PHP 7 & MySQL: An Object Oriented Introduction that I’ve been writing. (Only the first 6 chapters have been converted to PHP 7, and once the rest of the book is finished, all of it will be PHP 7 content and examples.) I only copied a few phrases from English to Bulgarian; so the book is written in English. (About 200+ pages currently.)

In case there’s a problem with Google Hangouts, I’ll have a streaming video of the talk available and communicate with the group via Twitter and/or email during the time of the talk. If you are not familiar with OOP, take a look at the first two chapters of PHP 7 & MySQL: An Object Oriented Introduction. Page 14 has a simple, clear and accurate definition of OOP that differentiates it from sequential and procedural programming.

Hope to see you via Google Hangouts on Saturday, February 13 at the Bulgaria PHP Meeting!

Share

PHP 7 / PHPNG: Speed and Better Data Typing

PHP7Hello PHP7

Last Wednesday (11/11/15), we drove up from Connecticut to the Boston PHP meeting where Zend’s Cal Evans gave a very informative talk on PHP 7 at the Microsoft New England Research and Development (N.E.R.D.) center next to the MIT campus. (PHP 7 is also known as PHPNG with NG = “Next Generation”.) It was well-worth the 200 mile (332K) round trip as my compadre (a Drupal guy) and I were examining every nuance of PHP 7 and what it meant for design patterns, functional programming and other PHP-based apps like Drupal and Word Press. The short version is that it means better speed. Fortunately, most of the other new features extend what we’ve been doing on this blog since its inception; namely, using mysqli instead of mysql; creating constructor functions using __construct instead of the class name; and using type hinting where possible.

Speed

I have not worried about speed for years. The bandwidth and processor speeds have regularly increased to the point where structure was more important than speed to me. Besides, there wasn’t much I could do about multi-core programming since PHP does not support concurrent development. (Maybe in version 8). I’ve already had a rant about my hosting service on my other blog; so I’ll not repeat it here; but get a hosting service that supports PHP 7.

So what about speed? It’s roughly twice what it used to be. Figure 1 shows some early timing data (which varies all over the place depending on the app you’re using). However, it does show how the speed since PHP 5.0 increased significantly. For the sake of argument, let’s say it’s about twice as fast as PHP 5.6.

Figure 1: Speed Comparisons with PHP 5.x and PHP 7

Figure 1: Speed Comparisons with PHP 5.x and PHP 7

If you’re doing professional development, you’ll want to wait until the official release of PHP 7 is out, but once it is, get yourself and your clients on a hosting service that supports PHP 7.

What Happened to PHP 6 : Abandonware

One of the questions asked at the presentation by Cal Evans was,

What happened to PHP 6?

I was thinking “vaporware” but that’s not fair nor accurate. Cal said that it was getting so on-off-on-off for a release, that it was simply abandoned to reduce confusion; so PHP 6 is “abandonware” but in fact about the only thing abandoned was the name. At the last minute one of the most important changes occurred when a huge speed improvement was introduced. Zend’s PHPNG (PHP Next Generation) engine is in head-to-head competition with HHVM (Hip-Hop Virtual Machine) from Facebook; so now with two engines competing for speed, let’s hope we all win in the speed of PHP. (Most of the speed data is from benchmarks based on the speed of numeric loops; so while speed is going to improve; don’t expect a rocket to the moon on most speed improvements.)

So What Effect Does this Have on OOP and Design Patterns?

From what I can tell; some affects to OOP may crop up, but not a lot as far as this blog is concerned. All of the examples on this blog have kept data typing strict: once a variable uses a data type, it doesn’t change. Likewise, type-hinting in parameters have forced only certain data types to be allowed in parameters. With PHP 7, type declarations are now available for scalar variables and return types. You should be able to add these declarations to any of the examples on this blog without an exception being thrown. All along we’ve been careful not to switch data types. One exception might be between integer and float types; so you might want to check there. Also, PHP 7 has a new integer divide function (intdiv()). The interval() function used up to this point will likely be replaced by the new intdiv() function where appropriate.

One of the new features that will definitely affect the way methods are written is the addition of return-type declarations. These work like the parameter declarations that have been used with object type (e.g., array, classes). So, for example, you can have something like the following:

<?php
class Infomaster
{
   private $members = 32;
   public function getMembers(): int
    {
       $groups=intdiv($this->members,5);
       return $groups;
    }
}
?>

The intdiv() function insures that the value will be an integer and the return type (int) is guaranteed. Throughout this blog, you should be able to use these kinds of type declarations without disrupting the code since care has been taken to be certain that everything is equivalent to a more strongly typed language.

What’s Next?

I’ve been waiting for the official release of PHP 7 before going ahead and finish my Sandlight CMS. This is for two reasons. My current Sandlight site is on a hosting service that is pretty far behind the curve in terms of current PHP and MySql. (e.g., I cannot use mysqli because their version of MySql is so out of date.) I’ve got to get a new hosting service, and unfortunately, the best one for what I want to do requires me to step up my IT Networking skills—get better at the command lines to work with installing PHP and the rest of LAMP files on a server that is basically carte blanche. Once I get to the point where I can program and develop, I’m good. It’s just the set-up that gives me the heebie-jeebies.

The other reason is that I want to use PHP 7 as a development language. I’m not going to worry about backward compatibility since I don’t have to support any lame web sites that some hacker built. Everything is going to remain both OOP with an increasing introduction of Functional Programming techniques that can be handled by PHP 7. I may use some Hack Language and install HHVM, but I prefer to use PHPNG with PHP 7. If I can, I’ll use both together. First, though, I have to go to the salt mines of the IT moles and get my system set up. Groan.

Share

Simple Functional Sniffer & Switch Alternative

mix Because PHP is a server-side language, you will have times that you need to rely on client-side languages like CSS, JavaScript and even HTML5 to accomplish certain tasks. In developing the CMS, I realized that while incorporating JavaScript, CSS and HTML5 in heredoc strings, I’d established a barrier between PHP and everything else by only allowing these other languages to interact with PHP through objects. Of course, this is because PHP has emerged into an OOP language and the others have not.

What I failed to take into account is the fact that it’s perfectly possible for OOP structures to interact with non-OOP structures. To some extend that has been done with HTML/CSS UIs and PHP design patterns in several examples. That seems to work out fine, but where you want to use dynamic variables for more responsive HTML pages, we’re back to encapsulating HTML (along with Javascript and CSS) into heredoc strings in PHP. There’s nothing wrong with that, and there’s much to be said for having a fully integrated OOP design pattern with a pure PHP engine.

A Simple Functional JavaScript Sniffer

The problem I discovered in a pure PHP design is that other design possibilities are overlooked. The primary style tool for HTML documents is CSS, and the media queries in CSS3 are designed to be responsive to different devices—namely, those brought about by mobile computing. Sometimes (and I do mean sometimes) that solution seems to work fine. Other, times, however, the media queries fail to capture that chunk of CSS3 code that formats for the desired device. On top of that, it can be difficult calling up certain jQuery mobile files—or any other files—from CSS alone. In many ways, libraries in jQuery have proven to be far more robust than CSS3 alone and far easier to deal with. In several respects, probably in most, neither CSS nor jQuery mobile are programming so much as they are styling tools. As such, they’re the tail of the programming dog. This is not to say they’re less important; they’re just not programming.

So, to sort out the devices looking at our pages, (moving away from CSS media queries) is a programming task. In several other entries on this blog, I’ve looked at ways to sniff through the possible devices, and I think we need to conclude once and for all that user-agents are next to useless. So, by exclusion, we’re left with screen width. So,begin by looking at this simple JavaScript sniffer using two lambda functions:

?View Code JAVASCRIPT
//Save as file name "jsniff.js"
var wide = screen.width;
var beta=function() {wide >=900 ? window.location.href="Desktop.html" :  window.location.href="Tablet.html";};
var lambda=function() {wide <= 480 ? window.location.href="Phone.html" : beta();};

In past posts I’ve used the Chain Of Responsibility (CoR) design pattern to do the same thing using either user agents (forget about it!) or width determined by a JavaScript object. The little JavaScript lambda functions do the same thing, and while at some point of granularity your may wish you had your CoR pattern, generally, I think that there’s enough with the three general categories at this point in time to deal with multiple device. Use the buttons to test the functions. (Try it with your phone and tablet too.) Click PlayA for the sniffer and PlayB for the PHP functional alternative to the switch statement. The download button downloads the source code for both.

PlayAPlayBDownload

The process is pretty simple both from a programming and a lambda calculus perspective. From lambda calculus we get following definitions of true and false:

true := λx.λy.x
false := λx.λy.y

As algorithms, we might consider the following:

function(x, y) {return x;};
function(x, y) {return y;};

So, that means:

function (10,20) = 10; ← true : Is 10
function (10,20) = 20; ← false : Not 10

That’s not exactly lambda calculus, but it’s along those lines that we can eke out an idea. (If you’re thinking, “What about function(10,10) that would appear to be both true and false,” you see what I mean.)

So now we’ll add the values a and b and reduce it:

((λx.λy.x) a b) -> ((λy.a) b) -> a

That replaces λx with (λy.a) b and then a. So a is a. Well, it sounds true!

Then for false we have:

((λx.λy.y) a b) -> ((λy.y) b) -> b

In looking at this, we see that if a is a its true; otherwise it’s b which is not true. That’s pretty much like if-then-else. If true a, otherwise it’s b.

So the line in JavaScript would be a ternary:

lambda = function(a) { return a ? a : b ;};

as well as in PHP,

$lambda = function($a) { return $a ? a : $b ;};

For now, that’s enough linking up lambda calculus with Internet languages. With our JS “sniffer” using a simple HTML call, we can get the page configuration we want for our device based on the window size:

<html>
	<head>
		<title>Functional Sniff</title>
			<script src="jsniff.js"></script>
	</head>
	<body onload=lambda()>
	</body>
</html>

Try it out. It’s easy to write and it’s practical. What’s more, you can see how close everything is to a Boolean type decision. (The different device HTML5 files are in the materials in the download package; one of which uses the jQuery Mobile formatting.)

I Don’t Need No Stinkin’ Switch Statement

One of the nice things about functional programming is that it made me re-think how I was programming. One of the areas where I thought I’d be able to boil down an algorithm to something more compact came when I decided to break down a calendar output into four weekly segment. Using a jQuery calendar, I could pick a day and pass the information to a PHP class for processing. Initially, the switch statement came to mind as a solution in something like the following:

$d=$this->numDay;
switch ($d)
       {
         case ($d >=1 && $d<=7):
            return "jquery";
            break;
        case ($d> 7 && $d<= 14):
            return "haskell";
            break;
        case ($d> 14 && $d<= 21):
            return "php";
            break;
        default: return "racket";
       }

In looking for a range, each case acts like a little function. So why not use lambda functions in PHP to do the same thing. Each query (case/function) either returns a value or goes on to the next case. Here’s what it looks like:

$gamma=function($d) {return $d > 14 && $d <= 21 ? "php" : "racket";};
$beta = function($d) use ($gamma) {return $d > 7 && $d <= 14 ? "haskell" : $gamma($d);};
$lambda = function($d) use ($beta) {return $d >=1 && $d <=7 ? "jquery": $beta($d);};
return $lambda($this->numDay);

The last used lambda function is the first in the list ($gamma). That’s because in order for the subsequent function to call them with the use statement, the function used must be defined before the one using it. In functional programming, the use of one function by another is referred to as a closure.

The Language Mix-Master

With the key parts in place, take a look at the different parts and languages used. First of all, the program begins with an HTML5 UI. It links to the jQuery UI JavaScript files and the CSS files. A further stylesheet links to the local CSS.

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8" />
  <title>jQuery UI Datepicker - Default functionality</title>
  <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
  <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
  <script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
   <link rel="stylesheet" href="lang.css">
  <script>
  $(function() {
    $( "#datepicker" ).datepicker();
  });
  </script>
</head>
<body>
  <h2>Language of the Week</h2>
  <h4>Click in the text box to select from pop-up calendar: </h4>
 <form action="LangWeek.php" method="post" name="useUI" target="showpix">
<p>Date: <input type="text" id="datepicker" name="pick" /></p>
<input type = "submit" value="Get Language" />
</form>
 <iframe name="showpix" width="300" height="300"></iframe>
</body>
</html>

A form links to a PHP file where it passes the selected datepicker() value. The iframe tag provides a visual feedback embedded in the HTML page. (Note: Remember, with HTML5, iframes are no longer evil.)

Finally, using a single PHP class, the selected date is reconfigured to an integer and evaluated by the lambda functions described above in lieu of a switch statement:

<?php
error_reporting(E_ALL | E_STRICT);
ini_set("display_errors", 1);
 
class LangWeek
{
    private $dateNow,$dayMonth, $numDay;
 
    public function __construct()
    {
        $this->dateNow = $_POST['pick'];
        $this->dayMonth=substr($this->dateNow, 3,2);    // Start 03  : 2Length
        $this->numDay = intval($this->dayMonth);
        echo "<img src='images/{$this->chooseLanguage()}' . '.jpg'>";
    }
 
    private function chooseLanguage()
    {
        $gamma=function($d) {return $d > 14 && $d <= 21 ? "php" : "racket";};
        $beta = function($d) use ($gamma) {return $d > 7 && $d <= 14 ? "haskell" : $gamma($d);};
        $lambda = function($d) use ($beta) {return $d >=1 && $d <=7 ? "jquery": $beta($d);};
        return $lambda($this->numDay);
    }   
}
$worker = new LangWeek();
?>

Fortunately the jQuery date picker passes the date as a consistent string mm/dd/yyyy, and so the only requirement is to use a substring to find the day of the month and convert it to an integer. This is passed to the chooseLanguage() method that employs the lambda functions.

Mixing it Up

While this blog is dedicated to PHP Design Patterns and their application, I believe that PHP programmers should explore beyond OOP and try out different kinds of programming within an OOP framework, which happily exists within a Design Pattern. The willingness to explore and experiment keeps programming fresh and interesting in any language.

Share

Sandlight CMS IV: Dynamic Responsive Web PHPages

responsiveAt this point in the Sandlight CMS development process, two design patterns have been employed: 1) Chain of Responsibility as a device checker, and 2) Abstract Factory for making different parts for different devices. As usual, I’ve been posting the results so far on the Sandlight Productions, LLC website. The site itself is the example used in this series. This post is Part IV of the Sandlight CMS series, and if you have not been following the series you can review what has been done so far beginning with Part I.

At this stage, the project is ready to use the Abstract Factory to produce the needed parts and put them together into a page. However, before going ahead and have the factory build the parts I’d like to take an intermediate step and just build a dynamic responsive Web page.

The Dynamic Responsive Web PHPage

The easiest way to proceed is to begin with an HTML5 page, encapsulate the page into a PHP object (class) and add methods. The reason for this step is that the Web site, in addition to being responsive, needs to be dynamic. This means that it needs a way for the administrator to add changes, and in order for this to transpire, the dynamic portion of the page has to include variables in the place of static text, graphics and/or video. Figure 1 shows the general layout envisioned for the page:

Figure 1: Dynamic Responsive Web Page

Figure 1: Dynamic Responsive Web Page

Everything about the page must be responsive, but some parts are static and some are dynamic. In the two-column outline in Figure 1, the entire left column is static yet it must be responsive to different devices. In Parts I to III of this series, the pages have been responsive. The next step in making them both responsive and dynamic is to create parts of the page that will be dynamic since they are already set up to be responsive. Before continuing, click the Play button to see the progress so far and the Download button for all of the source code and accompanying files:
PlayDownload

Using PHP alone, creating a dynamic page is simple. Just place PHP variables where content goes. This is true for both the pages formatted by CSS3 and jQuery. Importantly, though, all of the Web pages should be encapsulated into PHP classes, using heredoc string variables as has been shown in previous installment of this series.

QR Code: The New Responsive Component

Quick Response Code (QR) is a new necessity for Web sites doing business on the Web and for just about every other kind of site that wants to increase its exposure. Basically, using a QR Code reader in a mobile device (phone or tablet) automatically brings up the link coded in the QR image (a square with some squiggly block images.) That beats trying to to thumb in a URL on a tiny phone keyboard. The following two can be downloaded free (at the time of this writing.):

sandlightqrcodeI’m pretty certain that other smart phones have QR readers; so if you have something other than an iOS or Android operating system on your mobile device, an Internet search for “QR Scanner” will probably be able to locate one for you.

sandlightOnce you have a QR scanner, you need a coded image, such as the one to your right. Go ahead and scan it to see what happens. It should take you to the Sandlight Productions, LLC home page build on this CMS (updated.) On it you will find several more QR codes for links to sites related to Sandlight. You can get the coded images online at different sites. One site allows you to include your logo and choice of colors is QRCode Monkey. The QR code image in green to your left with the Sandlight logo in the middle does exactly the same thing as the black one. So, if you’d like your QR Code images to keep your graphic designer happy, consider the visual options beyond the default. Figure 2 shows a page being scanned with an iPhone (left) and the linked page in the iPhone (right).

Figure 2: Scanned QR URL uploaded in mobile phone.

Figure 2: Scanned QR URL uploaded in mobile phone.

Adding QR codes to your site (or your client’s site) is very easy, and you should definitely include it in your dynamic responsive CMS. Let’s now see how the dynamic responsive two-column page is created:
Continue reading ‘Sandlight CMS IV: Dynamic Responsive Web PHPages’

Share

Is PHP an OOP Gateway Drug?

gatewayIs OOP in PHP going to Help in Other Languages?

PHP is a great tool for working with both Web-based languages like HTML5, JavaScript, CSS3 and jQuery (actually a kind of JavaScript). Of course it’s an essential tool for working with SQL and the kinds of server-side operations that can only be done with a server-side language like PHP.

With the advent of mobile devices, PHP developers are able to add to help recognize devices through user-agents, but sniffers are plagued by both the vague information provided by the user-agents and may not be able to tell the difference between different screen widths and resolutions with the same user-agent information; like iPads and iPad Minis. Microsoft has the same user-agent id for all of their devices–“trident.”

Web Apps and Device Apps

PHP has been a great tool in Web app (applications that run in a browser) development for mobile devices, but these apps are largely dependent on an Internet connection, and unless there’s some way to add a local host to an Android-based Note or iOS-based iPhone, you rely on a connection to the Web. Even with WiFi being widely and generally available, an app that runs on the native Android OS or the Apple iOS (Device App) has lots of advantages over a Web app.

Don’t get me wrong. Web apps have tons of advantages over device apps when it comes to development and distribution. All devices that have browsers can run Web apps, but apps made for an Android will not run on iOS devices and vice versa.

So if you know PHP (and lots of other Internet languages), at some point you may have to bite the bullet and download the (free) Android and/or iOS SDK (Software Development Kit). The good news is that if you’ve been working with PHP OOP and design patterns, much of the code environment will look very familiar. The IDEs used by both the Android and iOS SDKs are very similar. The development process, though, takes place within classes and structures that you will be familiar with—depending on how much you’ve been experimenting with PHP OOP and design patterns.

For example, the following is a simple Swift class that generates a message—not too dissimilar from what JavaScript does with an alert() function.

import UIKit
 
class ViewController: UIViewController
{ 
    @IBAction func showAlert()
    {
        let alert = UIAlertController(title: "Sandlight Productions, LLC",
            message: "Messages for the World!",
            preferredStyle: .Alert)
 
        let action = UIAlertAction(title: "Sandlight", style: .Default, handler: nil)
 
        alert.addAction(action)
 
        presentViewController(alert, animated: true, completion: nil)
    }
 
}

Both the Android and iOS SDKs have lots of importable classes, and the imported UIKit has objects for the UI. The class declaration,

class ViewController: UIViewController

would be like declaring

class ViewController implements UIViewController

in PHP. So, while some different operators are used (e.g., : instead of implements) most of the statements are pretty close to those in PHP.

Some, though, are special to both the framework and the language. For instance,

@IBAction func showAlert()

does not have an equivalent in PHP for the whole method. The @IBAction connects the source code to a UI object. The showAlert() method, in this example, is connected to a button in the Interface Builder, part of the iOS SDK. Further, func is used instead of function used in PHP.

In declaring variables, Swift, uses the let keyword and the = assignment operator, and Swift does not use the new keyword in creating objects. For example, in Swift,

let alert = UIAlertController(//parameter list);

would be,

$alert = new UIAlertController(//parameter list);

in PHP. If you understand something about OOP and design patterns, this other type of programming makes more sense than if you do not.

Figure 1 shows the output on a simulator developed in the iOS SDK:

Figure 1: Landscape view of the alert in an iPhone 5s simulator.

Figure 1: Landscape view of the alert in an iPhone 5s simulator.

In and of itself, it’s no great shakes. However, it can be run anywhere and without a browser or an Internet connection. What’s important is that those working with OOP and design patterns in PHP are far closer to the languages used for Android (Java) and iOS (Swift). So if you start getting clients who demand to have their own apps to be downloaded to their phones and used without a browser, don’t be afraid to start making some simple ones. You can even create a device app that calls up a mobile app written in PHP and jQuery Mobile. The big advantage of that is you can access an SQL database.

Event Driven Programs and Programming: Not So Much PHP

If you’ve ever made a game—especially the arcade type—you’re probably familiar with “event-driven programming.” Languages like ActionScript, including OOP and design pattern designs, used to be used a lot in event-driven software development. The State design pattern is often used for event-driven programs since the states keep changing with new information from the user. The events are typically made up by the user tapping, sliding and dragging objects on the screen. PHP at some base is more of a data-getting and setting type of software. The getting and setting is done in conjunction with MySQL and the SQL language.

A lot of mobile app development is done with event-driven processes, and at least in the SDKs for iOS and Android, the frameworks are set up in classes and more state-like programming than you’ll see in most PHP. However, on this blog, the Client-Request model is easily applicable to event-driven kinds of applications. A number of PHP programmers have some interesting suggestions for event-driven programming and programs, but I’m not sure how well they’d work compared to languages like Python where the connections to the event-producing object (e.g., mouse/finger clicks/taps and keyboard entries) are more direct. PHP is a bit too dependent on HTML and JavaScript to handle events in client-side events.

In any event, using OOP and design patterns in PHP is very transferrable to other languages. The same is true in using the logic and structure of functional programming. So, if you’re thinking about jumping into either iOS or Android app development, you’ve be entering a familiar programming environment if you understand working with OOP and design patterns in PHP. Don’t be afraid of event-driven programs even though they’re not exactly common in PHP. The structures you will work in will be very familiar.

Share