Advanced Guide to PHP on IBM i

Working through many of the concepts and skills needed by intermediate and advanced PHP developers, this book is specifically designed to help good PHP developers become indispensable ones. Topics include debugging, test-driven development, web-based development, advanced object-oriented programming, and web security, and the book also takes an in-depth look at the new PHP Toolkit for IBM i provided by Zend Technologies. Upon completion of this book, readers will be able to use its principles as a basis for architecting complex applications, building web services according to the best standards currently available, significantly reducing the time spent discovering and fixing errors in code, designing architectures that are testable and predictable, building secure applications by protecting against most known attacks, and avoiding and preparing for common performance issues.

1136530712
Advanced Guide to PHP on IBM i

Working through many of the concepts and skills needed by intermediate and advanced PHP developers, this book is specifically designed to help good PHP developers become indispensable ones. Topics include debugging, test-driven development, web-based development, advanced object-oriented programming, and web security, and the book also takes an in-depth look at the new PHP Toolkit for IBM i provided by Zend Technologies. Upon completion of this book, readers will be able to use its principles as a basis for architecting complex applications, building web services according to the best standards currently available, significantly reducing the time spent discovering and fixing errors in code, designing architectures that are testable and predictable, building secure applications by protecting against most known attacks, and avoiding and preparing for common performance issues.

78.99 In Stock
Advanced Guide to PHP on IBM i

Advanced Guide to PHP on IBM i

by Kevin Schroeder
Advanced Guide to PHP on IBM i

Advanced Guide to PHP on IBM i

by Kevin Schroeder

eBook

$78.99 

Available on Compatible NOOK devices, the free NOOK App and in My Digital Library.
WANT A NOOK?  Explore Now

Related collections and offers

LEND ME® See Details

Overview

Working through many of the concepts and skills needed by intermediate and advanced PHP developers, this book is specifically designed to help good PHP developers become indispensable ones. Topics include debugging, test-driven development, web-based development, advanced object-oriented programming, and web security, and the book also takes an in-depth look at the new PHP Toolkit for IBM i provided by Zend Technologies. Upon completion of this book, readers will be able to use its principles as a basis for architecting complex applications, building web services according to the best standards currently available, significantly reducing the time spent discovering and fixing errors in code, designing architectures that are testable and predictable, building secure applications by protecting against most known attacks, and avoiding and preparing for common performance issues.


Product Details

ISBN-13: 9781583477656
Publisher: MC Press, LLC
Publication date: 04/01/2014
Sold by: INDEPENDENT PUB GROUP - EPUB - EBKS
Format: eBook
Pages: 400
File size: 10 MB

About the Author

Kevin Schroeder is the technical manager for education and consulting for MagentoU and a former technical consultant for Zend Technologies. He is the author of You Want to Do What with PHP? and the coauthor of The IBM i Programmer's Guide to PHP. He lives in Frisco, Texas.

Read an Excerpt

Advanced Guide to PHP on IBM i


By Kevin Schroeder

MC Press

Copyright © 2014 Kevin Schroeder
All rights reserved.
ISBN: 978-1-58347-765-6



CHAPTER 1

A Re-Introduction to Basic Concepts


We will start this section with a (very) quick re-introduction to the basic concepts of object-oriented programming (OOP).


Classes and Objects

When it comes to OOP, the most basic discernible concept is the class. The class is the foundation of everything that follows it. You cannot have an object without a class. An interface is largely pointless without a class. Abstract classes refuse to instantiate. Sometimes that class might simply be a definition that says an object of said type can exist, and other times it can be part of a much larger grouping of functionality.

As a general starting point, think about a class as the definition of a reference in an application to a real thing. Although, in practice, objects rarely are accurate representations of a thing, it is a good starting place for your understanding. It is much the same as in real life.

Consider from within the world of biology, which has many different taxonomic groups, such as Plants, Fungi, and Animals. You can break down these groups into even more distinct categories; for example, you can sort the Animal group into Fish, Birds, and Mammals, and then divide the Mammals group into yet more distinct categories like People, Dogs, and Kittens. These are examples of classes. They are definitions of what could be. An object is when you give form to that definition. You do not just have a person, but you have a "Kevin" or a "Bob." An individual can be likened to an object, whereas taxa can be likened to classes. It is the relationship of definition to instance.

When defining a class, you can define three general types of things: properties, methods, and constants. Let's look at an example that encapsulates about 80 percent of what you will be using when working with OOP:

[PROGRAM LISTING NOT REPRODUCIBLE IN ASCII]


Properties

Think of a property as a variable attached to an instance of a class. It will contain only data and no logic. In this case, you have two properties: $name and $breed.


Methods

Methods are the class version of a function. A method is basically a function that is tied to a class, and where you will implement any logic in the class.

In this example, you have two methods: setName() and setBreed(). The setBreed() method contains a little logic that allows only defined breeds to be set for the instance's $breed property. By setting the $breed property as private (we will look at what that means in a bit), you ensure that the only way to set that property is by calling the setBreed() method.


Constants

Classes can contain data that is consistent, or constant, across multiple instances of a class. This technique is often used as a means to introduce defined predictability. In the previous example, you would not be allowed to enter just any breed; instead, you must enter one that the class has defined as valid. And one of the easiest ways of doing that is by providing the constant name rather than a defined value.

The following code shows how you might be tempted to set a breed:

$macy = new Dog();
$macy -> setName('Macy');
$macy -> setBreed('Corgi');


But go back and look at how you defined the constant representing a Corgi. Notice the difference? The code example here uses an uppercase "c," whereas the class definition is all lower case. So by providing the string value, you might have accidentally introduced inconsistency into your data.

However, when you use the constant, you are saying, this dog is a Corgi, according to my definition. And by doing so, you reduce the risk of accidental mistypes on the keyboard and provide a much more predictable use case:

$macy = new Dog();
$macy -> setName('Macy');
$macy -> setBreed(Dog::BREED_CORGI);


Context

Context is the nature of our interaction with a definition. When you interact with static context, you are working with the class itself. Any logic can be executed from any class instance, can affect other instances, or might not be related to an instance of that class at all. To some degree, we can liken it to procedural functionality within a class structure. This is not entirely true, but it's accurate enough for a base definition. If working from within the object context, you are interacting not with the class, but with the instance of that class.

Two important keywords to know are self and $this. Because self refers to the class definition, it is somewhat global in its scope — not global like a global variable, but simply globally accessible. You can define the static context as a property (self::$breeds) or as a method (self::addBreed($breed)).

However, you can use the self keyword only when you are working within the class definition itself. If you are working within the global context or calling from within another class, you must specify the class name to call it:

Dog::addBreed('beagle');


When working in the object context, you generally use the keyword $this. It is a reserved variable name that simply refers to the current object instance. So if you have two instances of the Dog class — one for Macy and another for Sasha — calling setName() sets the property for the individual instance, which means that $this->name will have a different value depending on the instance of the object that you are working from within.


Visibility

When working in OOP, you have three levels of visibility: public, protected, and private, as Table 1.1 shows.


Abstract Classes

Sometimes a class can have some functionality defined in it, but not enough to let it instantiate. Or it has additional functionality that will diverge at further levels of taxonomic completeness. For example, fish can share certain commonalities such as fins, scales, and cold-bloodedness. But if you were to add gills to that list, you would be wrong. Some fish (called the lungfish) have lungs. So although you can define the Fish class to a certain extent, you cannot include the breathing mechanism because it can be completely different based on the type of fish.

Therefore, you need to define the Fish class as abstract and add functionality in later implementations:

[PROGRAM LISTING NOT REPRODUCIBLE IN ASCII]


Then when you later define Fish, you can include the breathing mechanism (e.g., gills for trout and lungs for lungfish).


Interface Definition

If classes are the definition of an instance, as "human" is to an individual, then interfaces are the expectations. But unlike classes, interfaces do not contain implementation details. That is because an object frequently needs only to know that something exists, not how it exists. And often that something might be an item that is not instantiated within the class itself but is injected from the outside. When that happens, the outside item might include a wild range of functionality that does not matter to the main object. For a better understanding, look at the following example.

Imagine you are designing a car. You have a base class called Car, which defines all the functional elements of a car: engine, doors, wheels, and so on. But does the car itself, the object that represents a real thing, need to know the implementation details of the engine? Does it need to know whether it is a 4-, 6-, or 8-cylinder car? Not really. It just needs to know that it has an ignition and a fuel supply control:

[PROGRAM LISTING NOT REPRODUCIBLE IN ASCII]


So when you define the Car class, you can add the engine to it but need not worry about how the Engine class does what it does. You care only about the interface to it. So you define a setEngine method that allows only a class of the Engine interface to be provided. The actual implementation does not matter to the Car class; the only concern is that it is actually an engine:

[PROGRAM LISTING NOT REPRODUCIBLE IN ASCII]

In the following example, TwelveCylinderEngine is an actual class that implements all the methods you require it to have as a class that has the function of the engine. To do this, you use the keyword implements (I will spare the details of actual implementation):

[PROGRAM LISTING NOT REPRODUCIBLE IN ASCII]


Now when you want to use the class, just write some simple code:

[PROGRAM LISTING NOT REPRODUCIBLE IN ASCII]


Because the class TwelveCylinderEngine implements Engine, the object will accept it as a parameter. If you try to define the engine as Transmission, the method call will fail with a fatal error.


Polymorphism

Polymorphism is the ability to define something that has more than one form. The fish and engine examples both demonstrate this in action. The word comes from the Greek roots "poly" and "morph" and means many shapes or many forms. But it is more than just defining something. Morph actual means one of various distinct forms. In other words, it is again a sort of taxonomy: an ordered, usually hierarchical, organization. When you look at how classes are structured within the larger context of a whole application, you will often see a hierarchical relationship of greater and greater levels of specificity.

That is why in the engine example you could act on the engine regardless of its actual implementation:

[PROGRAM LISTING NOT REPRODUCIBLE IN ASCII]


Because the requirement specified that the variable be of a type Engine, it did not matter how many cylinders the engine had. From the car's viewpoint, it was an engine, and that was all. So the engine object was one of various distinct (cylinders, for example) forms. And this plays nicely into the next area of review.


Type Hinting

By using type hinting, a class designer can enforce the object type when passing in various parameters. To do this, you define the type of object that needs to be passed, usually at its lowest usable hierarchical member. For example, if you had a class that represents a Honda Accord, you would not place a 12-cylinder engine in it, as much fun as that might be. As a designer, you can use type hinting as a means of restricting the types of objects that can be passed into a method definition.

You already saw an example of this in the Car class:

[PROGRAM LISTING NOT REPRODUCIBLE IN ASCII]

The Engine value for the setEngine() method defines the type hint for that parameter. PHP will not let a variable of other lower or disparate types be passed in that parameter.

If you extend the Car class to HondaAccord, you can further restrict the subclass of Engine that is passed:

[PROGRAM LISTING NOT REPRODUCIBLE IN ASCII]


With that, we wrap up the basic review of object-oriented programming. I based this review on the chapters in my earlier book. So if any of the OOP concepts or techniques seem too foreign to you, or you need to learn more about the fundamentals, pick up a copy of The IBM i Programmer's Guide to PHP for a more basic introduction to OOP.


Namespaces

PHP 5.3 introduced a long overdue feature to its object-oriented system. Namespaces allow for the distinct separation not only of classes (with their properties, methods, and constants) but of groups of classes as well. Before PHP 5.3, namespaces were available simply because a namespace is just that — a "name space." In pre-PHP 5.3 applications, the only "name space" for classes was global. With PHP 5.3, developers now have the option of dividing class definitions into more distinct subunits, called namespaces. The extra "s" at the end of namespace implies that more than one is available. (Although this is not technically the reason for the additional "s," it might help you form a picture in your mind as to how namespaces operate.)

But if all namespaces do is provide a means of naming things more clearly, are they really that useful of a feature? Actually, yes.

Presume, for a moment, that you are part of a larger development team working on an application. Some of the functionality that you have to implement needs a class called File. Nice and distinct, and there is only one way to define a file, right?

Sure, but what if that file is a row in the database that is representing a virtual file? "No problem!" you might say, "I'll just use PSR-0 and call it Database_File."

At which point I would say, "You mean Core_Database_Filesystem_VirtuaLFile?" A look at any modern PHP framework can provide examples as to how deep the psychosis can go.

Defining a namespace is easy. Before you define the class, simply use the keyword namespace followed by the name of the namespace:

namespace MyNamespace;

class MyClass
{

}


The way you would have had to instantiate this class in earlier versions of PHP would have been to use the underscore (_) pseudo-namespace separator. But now, if you instantiate the class from within that namespace, you can do so without specifying the namespace. If you are within a given namespace, its name is presumed by the Zend Engine:

[PROGRAM LISTING NOT REPRODUCIBLE IN ASCII]


But what is the object's actual class name? MyClass, right? Let's add some code to see what happens:

[PROGRAM LISTING NOT REPRODUCIBLE IN ASCII]


Running this code produces the following output:

MyNamespace\MyClass


What is that backslash doing there? Nowhere in the code did you enter a backslash. But in PHP, the backslash is the namespace separator. You use it to delineate the namespace from the class and to note child namespaces.

Developers who program with languages like Java might find this convention takes some getting used to. That is because the backslash is also universally used as an escaping operator, and most languages, such as Java, use periods to denote namespace relationships. But in PHP, periods are already used for string concatenation, so deciding which character to use to denote namespaces is a little harder.

When storing source files for namespaced code, you generally use the same naming convention as with pseudo-namespaces. But instead of translating underscores to path separators, you translate backslashes to path separators. So, for example, a class called MyClass in the namespace MyNamespace would reside in the directory MyNamespace/MyClass.php.

From the perspective of an autoloader (a special function/method that loads class definitions when they are first referenced), the logic to load the class would be thus:

[PROGRAM LISTING NOT REPRODUCIBLE IN ASCII]


When you try to access a given class that has not yet been included in the current request scope, this autoloader will translate the file name to MyNamespace/MyClass.php and attempt to load it. Note, however, that this function does not work with pseudo-namespaced classes because you have not taken underscores into account.

Do you need to follow the structure where directories match the namespace values? No, not at all. In fact, you can do whatever you want and simply define namespaces for the fun of it, as long as your autoloader can accommodate the structure. But the purpose of having namespaces is to let you define multiple working areas within your code and do so in a predictable fashion. So although you can ignore naming conventions, following them as described here is much more beneficial.

So how do you work from within multiple different namespaces?

Let's start with a namespace called Util that will contain classes that have a general purpose, or utility, across an application. The namespace Util will have a class called Date that you will use for some generic date-processing functionality. You will store this class in a file called Util/Date.php (and store it in the directory /lib, which presumably is set in the include_path):

[PROGRAM LISTING NOT REPRODUCIBLE IN ASCII]


If you created an instance of this class from within an index.php file, you would have to call it from within the global scope. You could, of course, define the code in index.php to be within the Util namespace, but that would go against virtually all accepted practices.

The index.php file looks like this:

$date = new Uti1\Date();
echo $date->getDate();


Note the use of the backslash when creating the new instance. Also note that the example did not include a leading backslash. This is interesting, as you will see in a bit. But for now, let's examine how to access classes from a distinct namespace.


(Continues...)

Excerpted from Advanced Guide to PHP on IBM i by Kevin Schroeder. Copyright © 2014 Kevin Schroeder. Excerpted by permission of MC Press.
All rights reserved. No part of this excerpt may be reproduced or reprinted without permission in writing from the publisher.
Excerpts are provided by Dial-A-Book Inc. solely for the personal use of visitors to this web site.

Table of Contents

Chapter 1: Beyond Basics OOP
Chapter 2: Debugging
Chapter 3: Security
Chapter 4: SPL
Chapter 5: Working with the Browser
Chapter 6: Web Services
Chapter 7: Test-Driven Development
Chapter 8: Using the Toolkit
Chapter 9: New Features in PHP 5.3, 5.4 and 5.5
Chapter 10: Performance Considerations
From the B&N Reads Blog

Customer Reviews