One of the most difficult parts about understanding someone else’s code arises when their coding style follows a different set of conventions than you do, or worse, no conventions at all. To help developers approach one another’s code more easily, the most common coding conventions have been gathered by the helpful people at Zend into a set of coding standards that you can employ to help ensure that the greatest number of people will be able to easily follow your code. I’m just going to introduce you to the standards they recommend. I won’t try to cover every detail – it’s a fairly long document – but if you want to learn more than just what’s in this video, check the file included with this presentation.
The coding standards suggested by the engineers at Zend have been released to the public under the same BSD license that covers Zend Framework, which means anyone can distribute or modify it to suit their needs. However, I am supposed to keep the copyright statement with it. Very briefly, here’s their license:
{show slide ?} http://framework.zend.com/license
The first topic covered by the coding standards is file formatting. Probably the most important takeaway from this section is the fact that files containing only PHP code must not contain a closing PHP tag ‘?>’ because it could risk introducing whitespace. New programmers in PHP often don’t realize this, but you don’t need to end your PHP scripts with any tags. The only reason you should need the ‘?>’ tag is if you’re mixing non-PHP code, such as HTML, with your file. And if you do introduce whitespace, say while including a file before the headers are expected to be set, it can screw up your script’s calls to start_session, header, or set_cookie functions (among other things).
Other points in this section – use 4 spaces to indent your scripts rather than tabs (since tabs can render inconsistently across editors) and line-lengths should be limited to 80 characters as much as possible, and have an absolute limit of 120 characters. This just prevents line-wrapping from making your code hard to read. And the last thing it mentions is how lines should end with a single newline character – the ASCII character 10, hex character 0X0A. Now, I’ve set up my code editor environment to implement each of these conventions. If you use Zend Studio, here’s how I set my editor to follow these conventions:
{open text editor settings page}
I got here by going into my preferences, then selecting ‘General’, ‘Editors’, and then ‘Text Editors’. Notice I set my ‘displayed tab width’ to 4, and checked the box for ‘replace tabs with spaces’. That lets me use tabs while I code, but actually inserts spaces. And then lower down I checked the option to display print margin, and set the margin to 80 characters. It shows up as a thin gray line in my editor that I try to keep my code inside as I write it.
Last, to get the correct line ending characters, I selected the workspace menu, and switched my new text line ending character from default to ‘Unix’.
The next section in the Coding standards deals with naming conventions.
Classes should be capitalized. And the name of the class should match the name of the filepath where the class can be located, with the underscore character in place of the path separator.
So, the class ‘Report_Display_Column’ would be located in the file Report/Display/Column.php. Personally, however, I follow the convention of ending my class-containing files with ‘.class.php’. The standards used by Zend make no preference either way, so don’t feel like you need to do the same. I just think it makes it clearer for you when you’re reviewing the files I’ve included with a lesson.
Each character immediately after an underscore should also be capitalized, and there should be no cases of consecutive capital letters. So, for example, ‘Report_Display_HTML’ would be an invalid classname, but ‘Report_Display_Html’ would be fine.
Other PHP files that do not contain classes should always end in .php, and filenames may only contain alphanumeric characters, the underscore, and the dash. Spaces in filenames are singled out as being very bad.
When it comes to naming your functions and methods, they should always being with a lowercase letter, and consist of only letters and numbers. However, numbers are discouraged unless there’s a really good reason. For instance, if you think ‘html2Text’ is more readable than ‘htmlToText’.
When a function name includes more than one word, it should be written with the follow-on words capitalized. In developer-speak this is often referred to as camel-case. And verbosity is encouraged. A long function name that clearly identifies what that function does is a good thing. In the case of a class method that has been declared private or protected, its name should begin with the underscore character. And that is the only case where it is appropriate to have the underscore character in you method names. The ability to set visibility on your methods and properties is new in PHP 5, so if you’re not familiar with this, don’t worry, since it gets covered in another section of this tutorial.
As for variables and class properties, they follow the same rules as functions. Camel-case with descriptive names. Very short names like $i or $n are permitted only in the situation of very simple loop counter variables. And, as a general rule of thumb, ‘very simple’ means 20 lines or less. If your loops go longer than that, then even your loop counter variables ought to have longer names.
One other note, if a class property is declared private or protected, it should begin with an underscore, just like a private or protected class method.
The last naming convention applies to constants, and that includes class constants and constants created with the ‘define’ function. They should be named with all capital letters, and if a constant’s name consists of more than one word, the words should be separated with underscore characters. Use descriptive names to make it easier to understand what a constant is going to be used for.
February 01 2010 | Schmategories | Comments Off on Coding Standards – part I: File format and naming
PHP 5.3 introduced the ability to create and use functions on the fly without naming them. When this technique is employed we refer to those functions as anonymous. Probably the most common situation for anonymous functions are when you need to specify a callback function. Here’s an example:
{show example with usort}
This example takes an array and sorts it alphabetically by last letter, rather than first. The usort function is one of many built into PHP that accepts a callback function.
You don’t have to use the PHP built-in functions to use anonymous functions though. You can create your own functions and methods that accept functions as parameters. Here’s one example:
{show example}
However, you can get the exact same behavior in both cases by declaring the function normally and passing a string representing the name of the function. One reason why you might prefer anonymous functions is that you don’t have to worry about naming collisions. Two functions can’t have the same name in PHP or a fatal error gets thrown.
If you want to access your anonymous function multiple times, you can assign it to a variable, like this:
{show example}
Technically, the variable $myFunc is an object of the PHP internal class Closure. The Closure class cannot have properties and has no callable methods. So, from a practical standpoint, using it is little different from having a string assigned to your variable that represents a function’s name. The only difference is that you aren’t at risk of having a naming collision with another function, and if you call ‘is_object’ on it, it’ll return true.
If you want to do recursion with an anonymous function, you’ll need to accept an argument that represents your function. When invoking it, just pass the variable representing your function as that argument. Here’s the classic factorial function as an anonymous function:
{show example}
You can use type-hinting to ensure that you’ve been passed a function. Just type hint as ‘Closure’. But there isn’t a way to be sure that you’ve been passed the same function, so recursion with anonymous functions definitely has its drawbacks.
PHP provides a handy method to use to test whether a variable can be invoked like a function before you make the attempt. It’s called ‘is_callable’. Technically, it accepts 3 arguments, but simply passing in the variable you want to test will get you a true/false response as to whether or not you can use it. Here it is in some code:
{show example}
Anonymous functions allow you to be very flexible with your coding. If you’re a fan of design patterns, anonymous functions are a handy way to implement the Command pattern. That’s one where you set up an implementing object of some sort that takes and invokes commands, without needing to know anything about them. As the name suggests, it’s a good pattern to use when you need the ability for your objects to do lots of different things that can’t all be defined in advance.
January 31 2010 | Schmategories | Comments Off on Anonymous functions
In this video, I want to introduce the basic SQL syntax for Select statements. In all likelihood, 90% of your queries you’ll need for your dynamic website can be handled by knowing just a very few SQL statements.
The most basic Select statement is:
SELECT * FROM `Table`
This returns a result set that contains every column of every record in `Table`. Now, using PHP, you could slice, sort, and filter those results any which way you please. And there are some rare situations where that’s probably your best bet. But for 99% of all cases, you’re much better off, performance-wise, doing that sort of manipulation to your data directly in your SQL query.
For instance, suppose we only need a subset of the results in a table. There are 2 ways we can limit our results. The first way is with a WHERE clause. That might look like this:
SELECT * FROM `Table` WHERE `productID` = 15
In this case, only records with a produceID column value of 15 will be returned. And filters can be as simple as the one above or much more complex. In addition to the ‘=’ operator, you can use != to specify that a column should not match the expression, as well as ‘LIKE’ or NOT LIKE with text values to do the same thing. Your WHERE clause can even use regular expressions with the EREG operator. And you can combine as many different WHERE clauses as you like using AND, OR, and XOR, along with parenthesis. For now though, we’re keeping things simple.
Now, one other way we can limit our results is to use a LIMIT clause. A LIMIT clause will work with or without a WHERE clause, and it will simply return up to the number of results specified. Here’s one example:
SELECT * FROM `Table` LIMIT 10
This result set will contain only the first 10 records in Table. And combining it with the WHERE clause from before, we get:
SELECT * FROM `Table` WHERE `productID` = 15 LIMIT 10
Just so you’re aware, the order of these fields does matter. A LIMIT clause always comes at the end of a SELECT statement. In this case, we’ll get a result of just the first 10 records where productID is 15. And if there are less than 10 records that match, all of them get returned.
Now sometimes, in fact usually, we’ll use a LIMIT clause that lets us specify records other than just the first ones that match. For example:
SELECT * FROM `Table` WHERE `productID` = 15 LIMIT 20, 10
In this case, we get records 20-29, instead of 0-9. The first number tells MySQL which starting record to return, and the second number is how many records to return from that point.
However, sometimes we want to order our results by a specific column, and MySQL lets us do that too with the ORDER clause. The ORDER clause always comes near the end of a SELECT statement. Only the LIMIT clause can come past it. Here’s a simple example:
SELECT * FROM `Table` ORDER BY `name`
The result set will be all of the columns and all of the rows, ordered by the column `name`. Assuming `name` is a string, such as a VARCHAR, the results will be ordered alphabetically. If we want to have them ordered reverse alphabetically, we can instead use:
SELECT * FROM `Table` ORDER BY `name` DESC
And the ORDER BY clause can actually specify more than one column. For instance, suppose there was a match in more than one record. To determine the order of records that have the same value for the primary sorting column, you can specify a secondary sorting column. So, let’s say we want to order `Table` by `productID` first, and by `name` second. That just looks like this:
SELECT * FROM `Table` ORDER BY `productID`, `name`
And now let’s combine the ORDER BY clause with WHERE and LIMIT
SELECT * FROM `Table` WHERE `productID` = 15 ORDER BY `name` LIMIT 10, 5
What happens here is that MySQL pulls out all the records that have a productID value of 15, orders them alphabetically by their name columns, and then from that set, returns the 5 records 10-14.
Now, supposing you only wanted a few of the columns returned, and not every column in every record for your result set. Just replace the * with the names of the columns you actually want. For example:
SELECT `name`, `productID`, `date`, `supplierID` FROM `TABLE`
Now I’m back to getting every record in my table, but for each one I only get the columns for `name`, `productID`, `date`, and `supplierID`.
That’s it for part 1 of building SQL SELECT queries. In part 2 we’re going to look at what you do when you want to get data from multiple tables instead of just 1.
January 30 2010 | Schmategories | Comments Off on Basic SQL Select queries
As we’ve already seen, PHP has introduced a lot of new features to support object-oriented programming. The one we’re looking at now deals with a special concept known as abstraction.
Now, abstraction in OO terms is similar to what it means in regular language. We talk about something being abstract when we deal with general patterns or themes, but no concrete details. And just like in life, PHP coders use abstraction to identify fundamental strategy and overarching design without getting bogged down in the nitty-gritty implementations.
When it comes to classes and objects, there are two key tools to explicitly support abstraction provided by the PHP 5 language. Interfaces and abstract classes.
We’ll start by taking a look at an abstract class. A class is abstract if it contains abstract methods. And a class can contain abstract methods by either explicitly declaring them or by extending a class with abstract methods and then not defining them.
The keyword you use on the class is, simply enough ‘abstract’. You use the same keyword on the methods. Here’s a simple abstract class that defines one abstract method:
{show example code}
Notice that the abstract method declaration looks sort of like a regular method declaration, except it contains the keywork ‘abstract’ in the front and ends with a semi-colon instead of braces. That’s because it only defines a method’s name and arguments, and not any of its implementation.
The idea here is that you might have many different child classes that extend an abstract class and implement its abstract methods in various ways. Without knowing the specific implementation, your other objects can interact with those child classes.
Now, the important thing to understand is that you cannot get a new instance of an abstract class. PHP will only create objects of non-abstract classes. If you want the functionality that an abstract class provides you must extend it into a non-abstract class that defines all its abstract methods.
For instance, if I define an abstract class called ‘Report’ with an abstract method called ‘display’, my other scripts know that regardless of which type of report I might have, it will always be able to display itself. I might define a Report_HTML child class for displaying a report inside an HTML table. I might define another one called Report_CSV for outputting a version of a report that can be saved in a CSV file. And I might define another one called Report_XLS for saving a report to an Excel Spreadsheet.
The point is that there are going to be many different scripts involved in getting data to the report or working with the report, and most of them don’t need to know how the report is going to be displayed in order to do their work correctly. So, rather than creating completely separate classes for each situation, we create one report class that has just one abstract method that needs to be defined separately in its child classes. This lets us use the same code in as many locations as possible, and code re-use leads to easier maintenance and management.
Since I like to point out design patterns from time to time, this is a good time to mention one called ‘Decorator’. The Decorator pattern is probably the one most often used by programmers who don’t even realize they’re implementing an actual named pattern. All it is is using child classes to add more specific functionality to parent classes. Extending an abstract class is one obvious way to accomplish that.
The other abstraction tool is similar. While abstract classes are essentially regular classes that happen to have some abstract methods, interfaces are sort of like classes that only have abstract methods. Interfaces don’t define properties, though they can define constants. And while a class can only extend one parent class, abstract or otherwise, it may implement any number of interfaces.
Here’s how we define an interface:
{show example code}
Notice that it really does look a lot like a class definition. You don’t need the ‘abstract’ keyword on the method declarations, but they do resemble abstract methods nonetheless. And since the basic idea is that an interface defines a way for other objects to interact with them, interfaces may only define public methods.
To tell the PHP engine that a particular class is going to implement the methods defined in an interface, we use the keyword ‘implements’ in our class definition. And if a class implements multiple interfaces, we just separate them with commas. However, no class can implement two interfaces that both define the same method name.
Interfaces can extend interfaces, and in fact, they can extend multiple interfaces. To extend an interface, you just use the extends keyword, and to extend more than one interface you just separate them with commas.
{show example code}
One thing to note about interfaces is that since there’s no actual code, it is vitally important that you comment them fully. The method declarations on an interface tell the programmer the method’s name and the arguments it should accept, if any. But if one of those methods should return something, the only way to let the programmer know that is in the comments. Here’s an example of a well-commented interface:
{show example code}
Notice that each method’s comments clearly explain what the method should do, in broad terms. With this documentation, it is feasible to begin writing code that will use objects that implement a certain interface even before the implementing classes have been defined.
Objects of classes that extend abstract classes or implement interfaces are considered to be instances of those abstract classes or interfaces, the same as they’re considered instances of the classes that define them. This makes it possible to use type-hinting to specify that your functions and methods require specific interfaces or classes as arguments.
To understand how powerful type-hinting is in connection with abstraction, imagine you have an interface called Readable. Among other things, it defines a method called ‘readLine’ and another method called ‘hasNext’. ‘readLine’ is responsible for returning a string from some content source, and advancing an internal pointer, so that a subsequent call to ‘readLine’ will get the string that comes right after. The ‘hasNext’ method returns true if there is are any lines left to get, and false if there aren’t. Knowing just those two methods, I can write a function like:
{show example code}
My ‘writeFile’ function knows that it’s getting a Readable as its first argument, and will write it out to whatever filename it’s told to. It doesn’t matter if the particular Readable is based on another file, a stream, the contents of a database, or anything else. And I can trust that so long as my various Readable implementations correctly return the data they ought to, my writeFile function will work with any of them. This sort of versatility means I can create functions such as writeFile before I’ve even created the actual object types that will be passed into them.
So that’s abstraction in a nutshell. You create abstract methods with lots of documentation to explain what they’ll do, and then you write classes that define those methods in a concrete, useful way.
January 30 2010 | Schmategories | Comments Off on Abstract classes and interfaces – part 1
In PHP, programmers can take advantage of an unusual technique known as variable variables. Basically, if you have a variable named $one that equals the literal integer ‘1’ and then another variable named $first that had a value of the string ‘one’, then the value of $$first would resolve as the literal integer ‘1’.
Here, check it out:
$one = 1;
$first = ‘one’;
echo $$first;
{show output}
The 2 dollar signs together are what tell PHP to return the variable $one instead of just $first. It is possibly the most confusing single thing in PHP, and something that new developers are understandably thrown by the first few times they see it. It’s not something you see a lot, but when you do see it, it’s usually because the developer was trying to solve an unusually difficult problem.
Variable variables work on both sides of an assignment too. If I were to write:
$second = ‘two’;
$$second = 2;
A new variable ‘$two’ would be added to my scope, such that if I were to say:
echo $two;
I would see ‘2’ in the output. And yes, that confuses everyone at first. I’m still confused by some of this stuff.
One of the things I find most interesting in PHP is that you can also use variables to invoke functions. Check out this example:
$test = ‘hello’;
function hello() {
echo ‘Hello World’;
}
$test();
{show output}
And so you see that I can now use a variable to invoke a function.
As far as naming restrictions, the variable $this is reserved, and can’t be used in variable variables. And with variable functions, it won’t work for special built-in PHP functions known as language constrcuts. These include ‘echo’, ‘print’, ‘isset’, ‘unset’, ’empty’, ‘include’, and ‘require’. Other than that though, you’re pretty unlimited. And variable variables don’t even need to be legal variables. Check out the following code:
$test = ‘1test’;
$$test = ‘hello’;
echo $1test; //variable names can’t begin with numbers – get a fatal parse error
You’ll get a fatal error, but if you really want to, you can do the following to see that PHP really did create your variable, you just can’t use normal PHP syntax to view it directly because of the rules around variable names. What you can do instead though, is this:
echo ${‘1test’}; //prints out ‘hello’
That last example introduced you to the power of braces in PHP. PHP can do quite a lot with braces as an intermediate step. If you place a dollar sign in front of a statement in braces, and then place an expression inbetween the braces, whether mathematical, scalar, evaluable function, whatever – if the result can be turned into a string (other than the string ‘this’), PHP will use that result as though it were the name of a variable you were attempting to access. And expressions in braces can be nested.
Though, from a practical standpoint, that’s a good way to make your code a lot harder to read!
${”} = ‘Empty!’; //the empty string can be a variable!
${${”}} = ‘Weird?’; //nesting brace expressions looks weird!
${${${”}}} = ‘Spooky!’; //double nesting just looks downright spooky!
echo ${‘Weird?’};
echo $${‘Empty!’}; //prints out ‘Spooky!Spooky!’
{show output}
Now, this last example brings up an interesting point about the empty string as a variable. Consider the following:
${null} = ‘Hello’;
echo $$notSet;
The variable $notSet was, as its name suggests, not set anywhere in the code. When PHP looks at it for the first time, it gives it an assumed value of null. Unlike more strictly-typed languages, you can use a variable in PHP without declaring it or setting a value to it. It’s just null until you make it something else. And null can be cast a string – the empty string. So here’s the output to that example:
{show output}
This leads to one way to seriously make your code confusing. When someone looks at your code for the first time, trying to understand it, one of the first things they’ll do is look to see where a particular variable is declared. But consider a script that did this:
$$somethingStrange = ‘Hello’;
//lots of intervening code
echo $$lostYa;
If neither $somethingStrange or $lostYa were declared in the code, then what you actually get is the empty string being used as a variable to save the value ‘Hello’ and then getting invoked when the script echoes $$lostYa. Here’s the output to prove it:
{show output}
Even worse, if you defined a function called ‘Hello’, then you could invoke it by doing something like:
$$somethingStrange = ‘Hello’;
function Hello() {
echo ‘Hello World. How do you suppose we got here?’;
}
$$hahaYouDontKnowWhatsGoingOn();
Hopefully you’ll never need to deliberately make your code hard to understand, but if you do, just treat the empty string variable as a part of your code, and keep invoking or setting it with a different undeclared variable every single time. I’m sure it would quickly drive me nuts if I saw it. So actually, on second thought, let me just advise you to never ever do this, but if you see it in someone else’s code, then that’s what they’ve done.
Anyway, moving back to the subject of braces, they can sometimes be the only way to resolve ambiguities, such as when your variable variables involve arrays. Consider this example with no braces:
$$one[2]
How is PHP supposed to interpet that? Do you want to get the value of $$one and then get the value at its array index 2? Or do you want to get the value of $one[2] and then use that result as a variable? Without braces, PHP can’t do anything with that expression. If you want to use $$one as your variable, use:
${$one}[2]
If you want $one[2] as your variable, use:
${$one[2]}
Here’s both examples:
{show script}
{show output}
Variable variables have been part of PHP since at least as far back as PHP 3. However, the engineers have continued to innovate, devising more ways to let you use variables in place of the names of other variables, particularly now that PHP has added so much object support.
The first one, which has been supported at least since PHP 4, is variable properties. When you refer to an object’s properties, you usually use an arrow pointing to the property name, like so:
$obj->one
However, if we again assume that the value of $first is the string ‘one’, then you can point to the same property with:
$obj->$first.
Now, that’s how it looks in PHP 5. In PHP 4 you had to place braces around your variable, like so:
$obj->{$first}
That just tells PHP to evaluate the bit inside the braces first. But since PHP 5, the engine will do that even with the braces removed (though obviously braces don’t hurt, either).
Building on that, PHP 5 also introduces the ability to refer to method calls by a variable. So, if we want the call
$obj->one()
We can now use:
$obj->$first()
Wild, isn’t it?
{show output}
The latest versions of PHP don’t even stop there. In PHP 5.3, the engineers decided to support variable class names! So, if ‘One’ is a class, and $first is the literal string ‘One’ , then the following code will create a new object of your class:
$obj = new $first();
Isn’t that cool?
I wish I could name a common problem that these techniques solve, but really, it’s just one more thing in your toolkit, and there’s no telling when you’ll reach for it. But if you know this little secret, then every so often you’ll see some tricky problem, maybe involving a sort or a switch, where variable variables turn out to be a great way to build your solution.
I know this is a difficult topic to grasp at first, but once you accept that aliasing can be used in place of actual variable and function names, it starts to make a certain sense. On the other hand, if you find yourself still not able to grasp it, I can at least reassure you that everything else in this tutorial is easier.
January 27 2010 | Schmategories | Comments Off on Variable variables
While there are many changes to PHP 5 that I love, if I were forced to choose a favorite, it would probably be this next thing I’m going to show you. It’s called autoload, and what it lets you do is define a way of including files dynamically based on the names of classes that your scripts need to use.
The basic idea is you devise your own class-naming convention such that based on the name of any given class in your project, you can say which file holds it. And then, you create a function named __autoload that takes the name of any class and builds an include statement that ought to give you access to it.
This lets you be sure that only the files that need to be included actually are, rather than having to include every single file that might possibly hold a class that some part of your script will need later. And best of all, you create the function once, and then so long as you keep your naming convention, you never need to think about including class files again!
Probably the most common classname convention is where you represent directory separators as underscores in your class names. So, for instance, if your class is named ‘Really_Big_Long_Class_Name’ then it probably resides in really/big/long/class/name.php. Personally, I tend to use a variant of this convention, where instead of ending my class files with .php, I end them in .class.php. So anyway, here’s what the __autoload function that does that might look like:
{show example code}
However, there is a drawback to this technique. Namely, if you define a function __autoload, you can only have one autoloader function. That might not sound like much of a drawback, but think about what happens if you want to make or use a 3rd-party plugin. Well, a plugin needs to define how its own classes are going to be included, and redefining its own __autoload function for the entire website isn’t going to fly. Technically, it’d cause a fatal error if the __autoload function has already been declared somewhere else. Like any other function, you only get to define it once.
So for more complicated websites, you either go back to including all your class files manually, or you switch to the very cool spl_autoload_register function.
spl_autoload_register lets you define a stack of functions that each get checked, one at a time, in order, until the class sought is found. You can call it as many times as you like, adding a different path conversion algorithm each time. This is the strategy I recommend you use in your own code.
Now, I haven’t called your attention to it, but you may have noticed that in almost every script I’ve written that tests some class or another, I have a single include statement. All it says is include ‘autoloader.php’; . And my classes get imported correctly every single time.
Let me show you how autoloader.php actually works. Notice, I DON’T use the code example I just showed you. I could, and it would work, but this is something even better.
Remember how I said that the convention of representing directory separators as underscores in the class name is the most common one? Well, it’s SO common, that the PHP engineers provided it as a default. When I called spl_autoload_register with no arguments, it told PHP to go ahead and register its built-in autoloader. Because it’s actually built into the language, and coded in C, rather than PHP, this is actually going to perform file includes faster than the exact same algorithm coded into a PHP function.
There’s a couple other important lines in here. The first line, ‘set_include_path’ was necessary to make sure that my classes directory, where I’m keeping all my class files, is one of the include paths PHP checks when I try to use the include statement. The other line, spl_autoload_extensions, tells PHP that my class files will end in .class.php.
And that’s really it! If I want to use the exact same naming convention, but separate my class files into several different folders, I would just need to call the set_include_path again for each folder that might contain a class file.
January 24 2010 | Schmategories | Comments Off on The Autoloader
Design patterns are the techniques programmers use for solving some sort of programming challenge using objects. There are many, and I’d encourage you to learn more than what these videos have space to teach. But out of them, 2 of the most commonly used are called Singleton and Factory.
The simplest of these is the Factory pattern, here’s one way to represent it:
{show code example}
Like I said, very simple – a Factory pattern exists whenever you use one class to create another. But it can be extremely powerful. Essentially, it has your code avoiding the new statement for certain types of objects, and instead relying on a specialized class to build them for you.
The purpose of the Factory pattern is to make your job as a programmer simpler. The example I just showed you is sort of a silly one. With objects that simple to create, there’s not much point in using the Factory pattern. But this technique becomes very useful when the constructor for an object takes many different, complex arguments. Instead of looking up all the information needed to construct one of those objects every time, your Factory class builds them for you and sends them back to your scripts ready to use.
By employing the Factory pattern, you create a situation where one part of your code doesn’t need to know about what another part of your code does. And that’s when object-oriented programming gives you the greatest benefit. By making different parts of your code work without any need to understand what another part does, you can more easily expand functionality in one area without having to completely rewrite others. That also makes it easier to debug, and more effectively tackle a project as a team.
The next design pattern I want to look at is the Singleton, and it gets its name from the fact that, when you use this pattern, there can only be one instance of your class running at any given time.
{show example Singleton}
The basic way it works is you have a constructor that’s declared as private, and a private static variable, usually called $_instance. Then, you have a public static method called ‘getInstance’.
Because the constructor is private, you can’t call $obj = new Singleton() anywhere outside the class itself. When you want to get an instance of Singleton, you go through the Singleton::getInstance() method.
The getInstance method, since it’s on the Singleton class, is allowed to call ‘new Singleton()’. So, when you put in a call to Singleton::getInstance() it first checks to see whether self::$_instance is null or not. If it is, it says ‘self::$_instance = new Singleton();’. Next, it returns the value in self::$_instance.
And that’s really all there is to it. Since there can be only one instance of Singleton at any given time, you know that any change you make to any property on it will be still be reflected if you access it anywhere else.
Technically, in this example there’s nothing stopping your code from cloning a Singleton, but if you wanted to prevent that too, you could just create a private function called __clone. __clone is one of the magic methods php provides, and just like __construct can be used here to prevent an outside call to the ‘new’ statement, __clone can be used to prevent the ‘clone’ statement from working.
So, I created a very simple test script to show the Singleton in action:
{show test script}
And here’s the output from that:
{show output}
Notice, I call the ‘getInstance’ method twice, but the objects in both cases are actually the same. Even though I set the ‘data’ property on $singleton1, when I display the contents of ‘data’ on $singleton2, the value shows up there.
So why would you want a Singleton? Well, if there’s code you want to make sure gets run just once in setting up an object, but then have access to the results of that code all throughout your script, Singleton is a pretty good way to handle that situation.
Later on, when we look at setting up an object-oriented login system, we’ll employ a User class that’s a Singleton. We only want to check a user’s session one time per page load, so by putting that into the constructor of a Singleton, we can accomplish that. But then every time we need to get a user’s information, it will be available without having to re-check their session every time.
January 24 2010 | Schmategories | Comments Off on Basic Design Patterns – Singleton and Factory
In your work with classes, one of the most important things to understand is the difference between static and non-static methods and properties. The key distinction is that static properties exist in the context of the class, and non-static properties exist only in the context of an object.
Accessing static methods and properties from your scripts is easy. If they’re public, just use the name of the class, followed by a double colon, followed by the static property or method you’re accessing. For properties, you need to include the dollar-sign. Without the dollar-sign, PHP looks for a class constant with that name. Here’s a class called StaticExamples:
{show example}
It defines a static property called ‘$helloWorld’. Over here in my test script:
{show test script}
, you can see I just write StaticExamples::$helloWorld to access it. Here’s the output:
{show output}
Static methods cannot access non-static properties and methods, because no object context exists for them. For a static method, the variable $this has no meaning, and because it has no meaning, there is no point of reference by which a non-static method or property can be called. At least, not directly. I’ll explain this more at the end.
On the other hand, non-static methods have no problem accessing static properties and methods. With static properties, if it gets changed at one part of the script, that change is reflected anywhere else that property is checked. I realize with a name like static, you’d think it couldn’t change at all, but static properties act just like regular variables. And actually, they’re often a good replacement for global variables.
So, consider this class:
{show example}
It defines a static property called $_changeme, a non-static property called _changeMeNS (the NS stands for non-static), and two non-static methods called setProps and getProps.
Those two non-static methods have to be invoked on instances of the StaticExamples class. Notice that once you call setProps with 2 arguments, it sets the static property $_changeMe to the first argument, and the non-static property _changeMeNS to the second argument.
Here’s a test script I wrote to go along with this lesson.
{show example}
The first thing it does is create three objects of the StaticExamples class. Then it calls the setProps method on each. Once it’s done that it calls the getProps method on each and displays their outputs. Let’s look at that now.
{switch to output}
Notice that the property labelled ‘static’ is a 3 on all of them, but they each have a different ‘non-static’ property. The reason for this is that only one StaticExamples::$_changeMe exists. And every call to setProps was also setting the $_changeMe variable. And now that I’m checking that variable, only the last value of $_changeMe exists.
As for the ‘non-static’ properties, they persist with the objects where they were set. So $SE1’s non-static property is still a 1, and $SE2’s non-static property is still a 2. Each object contains its own copies of its non-static properties, but they all accessed the exact same static property.
Now, looking back at the code, I want to point out the keyword ‘self’. It’s sort of like a static equivalent to ‘$this’. Each time I used ‘self’ I could have used the full class name ‘StaticExamples’ instead. I used ‘self’ because it’s a convenient shorthand for accessing static methods and properties from within the context of the class.
Now, a static method cannot access a non-static method or property directly, as I explained before. See my static method ‘doSomething’?
{show example}
It’s going to trigger a fatal error as soon as I try to use it. Watch:
{type StaticMethods::doSomething(); into test script}
{show output containing fatal error}
However, if you really wanted to, you could create a static property which is itself an object of your class, and then you could use that static property, within your static methods, to run non-static methods and access non-static properties.
Notice I’ve written 2 more methods in my StaticExamples class, called setPropsStatic, and getPropsStatic. They’re similar to setProps and getProps, but can be called from a static context.
{show example code}
The way they work, is they first check whether the variable $_instance, a private, static property, is null or not. If it is, they set it to a new object of StaticExamples. And that property will still be set the next time one of these methods looks for it. Next they run whatever code they need to. Notice in ‘setPropsStatic’ it’s using self::$_instance to access a private, non-static property. When a static method creates an instance of its own class, it can use that instance object as a handle for accessing private and protected methods or properties on it. We’re going to use that fact later when I show you how the Singleton pattern works.
Now, going back to my test script, I’ll put StaticExamples::setPropsStatic(0,0); in front of my call to $SE1->setProps, and I’ll stick StaticExamples::getPropsStatic(); right before $SE1->getProps. Now let’s look at how the output has changed.
{show output}
Notice, the static property on getPropsStatic is a 3, same as all the others. But it’s non-static property is a 0, just like when it was set. That’s because in the context of StaticExamples::$_instance, the property _changeMeNS has only been set one time.
January 23 2010 | Schmategories | 1 Comment »
The developers of PHP were actually taken a bit by surprise when object-oriented programming caught on the way it did within the PHP community. Objects were added as an afterthought to PHP 3, and were little more than syntactic sugar for associative arrays. PHP 4 brought some advancements in object support, but with PHP 5, the language has finally graduated into a completely respectable object-oriented language.
Among the features that you expect to find in object-oriented languages is the ability to limit access to your objects’ methods and properties. The goal here is to avoid letting your scripts get into trouble by messing with things they don’t need access to.
As a for instance, suppose you have an object that’s responsible for handling your database transactions. And on this object there exists a property called ‘dbConnect’ whose purpose is to contain the resource that will let PHP run queries on a database. And you’ve done a great job putting together a class that will execute SQL queries, handle transactions, do updates, and really is just an all around beautiful piece of code. And you’d like to ensure that this dbConnect property, one that your class sets up in the constructor and then makes use of in a few key functions, only ever has the value you expect it to.
But in PHP 4, you would just have to write strongly-worded comments and hope that none of the people on your project would be foolish enough to try and get the dbConnect property directly, thereby completely by-passing your class’s way of doing things securely and efficiently. Or worse yet, have a script go in and directly modify the value of dbConnect. After all, you don’t want dbConnect to change unless the database name, host, user, or password were changed too. If an outside script modifies it directly, your object may not actually be running commands on the database it thinks its running commands on, and that might lead to a whole cascade of errors.
So to deal with this type of situation, PHP 5 says you can now specify that a class has certain methods or properties that can only be accessed by the class itself. All you have to do is put the keyword ‘private’ in front of the declaration.
As a convention, I recommend you put an underscore in front of your private or protected properties and methods. It’s a nice way to know, at a glance, whether you’re dealing with something that’s public or not. It’s a pretty common convention. I don’t know where it started, but it’s one I’m quick to endorse. {show example class definition}
Now, the obvious question you’re probably asking, is what’s the difference between private and protected? Well, neither one can be invoked by an outside script, but while private methods and properties can only be invoked by the classes that declared them, protected properties and methods can also be invoked by the children of the classes that declared them.
So, if _protectedMethod is a protected method on the class ParentClass, and ParentClass is extended by a class called ‘ChildClass’, then an object of type ‘ChildClass’ would be allowed to invoke $this->_protectedSpecial(). {show example}
On the other hand, ParentClass also defines ‘_privateMethod’ as a private method. If a ChildClass object tries to invoke $this->_privateMethod() it will trigger a fatal error. {uncomment call to _privateMethod and then show example triggering error}
However, while this is probably the most common way of accessing a protected property or method from a child class, it doesn’t have to be in the context of “$this” in order to work. Consider this next example: {show example method}
$parent = new ParentClass();
$parent->_protectedMethod();
Then in the context of being on ChildClass somewhere, this code will execute without an error. {show output from method accessing protected property and method this way}
{while explaining next P, show method declaration with no scope keyword, access it in public context, then go back and put keyword ‘public’ in front of it}
As for public, that’s technically the default for your methods. In PHP 4, all properties and methods were public, meaning they could be accessed or updated in any context. When you define a method, if you just write function <methodName>([<argsList>]) {… } with nothing in front of it, it’s public. See? {show output} However, in order to have my methods look consistent, I like to place the keyword “public” in front of my public methods. {return to declaration and write ‘public’} To me, it actually looks weird to see a method declaration without one of ‘public’, ‘private’, or ‘protected’ in front of it.
As for properties, they work the same way. To declare a property public private or protected, just put the desired keyword in front of its declaration. In PHP 4, properties were always preceded with the ‘var’ keyword. To preserve backwards-compatibility, this does actually still work. It just creates a new public property. However, since this technique is deprecated, you should avoid it.
The last keyword I want to talk about in this video is, no pun intended, “final”. The final keyword is used to prevent methods from being overwritten by child classes, or to prevent a class from being extended entirely. If a child class tried to re-declare a parent class’s final method, PHP would trigger a fatal error as soon as the file containing the child class got included.
I’ll show you:
{open ParentClass class file and place ‘final’ in front of a method declaration}
Since ChildClass also defines the ‘doSomething’ method, PHP is going to complain about it:
{show output with fatal error}
This is a great tool for situations where you know that, if a child class writes its own method that your parent class has already declared, then there’s a good chance that it’ll break your functionality. Just make that property or method final and you won’t have to worry about it.
The other way you can use final is by placing it in front of a class name in the declaration. This will prevent any class from extending it. And you can see that here: {place ‘final’ in front of ‘class ParentClass’}
{show output with fatal error}
That’s all for this video.
January 22 2010 | Schmategories | Comments Off on Public, private, or protected?
PHP 5 introduced a number of powerful upgrades to assist object-oriented programmers. The one we’re going to look at next is called magic methods. And as you can guess from the name, they’re pretty amazing.
First off, let me explain what makes a method “magic”. A magic method adds some additional functionality to your objects, and the way it works is by providing an interface through which the PHP engine can interact with them. {show website} As of this video, there are 14 magic methods, and I definitely want to encourage you to at least be familiar with all of them. The php manual at php.net has an excellent treatment of them, but right now, I’m just going to show you the 4 methods that I think you’ll probably get the most use out of.
Now, just so you recognize them, all magic methods identify themselves by having two underscore characters in front of their names. As a commonsense guide, you shouldn’t create them unless you specifically want the magic functionality. Some of these methods can be accessed directly like ordinary methods, while others can’t – if you want to know which are which, the best way to find out is to test. And since any magic methods added in the future will also begin with two underscore characters, it is strongly discouraged for you to begin any of your regular method names that way.
So, the first method I want to show you is called __construct. Like most magic methods, it should be obvious what it does just from its name. In this case, the __construct method gets called as soon as you create a new instance of your class. Whichever arguments you send in your call to the ‘new’ statement also get sent to the __construct method.
This function is called a constructor, and unlike the other magic methods, this functionality isn’t new to PHP 5. However, back before PHP 5, constructors were simply methods defined with the same names as the classes they were defined in. And, to preserve backwards-compatibility, this convention, while deprecated, does still work. If you have both a __construct method, and an old-style constructor, the __construct method will be the only one called during a ‘new’ statement.
The next 3 methods provide brand new functionality that PHP didn’t have before. The common theme here is that they automatically get invoked when your scripts attempt to access properties or methods on your objects that either aren’t defined, or aren’t declared as public.
The first method of these methods is called __get.
When you try to retrieve the value of a property that isn’t public, or doesn’t exist, before triggering a notice, PHP checks to see whether your object has one of these __get methods. If it does, then PHP will invoke it and pass in the name of the property requested by your script as the only argument. Here’s a simple example of a __get method:
{show example code}
Now, in this case, my class doesn’t define any public properties, but it does define a private property called _options, which is an array. So, whenever a property is requested, it checks to see if the _options array has a value set on the same key as the name of the property the script was trying to access. And if there isn’t one set, it just returns false.
The counterpart to the __get method is the __set method, and from the name, you can probably guess that it gets invoked when a script tries to set a property that isn’t public. This method takes 2 arguments. The first is the name of the property to be set, and the second is the value that the script tried to assign that property.
{show example}
In this case, the __set method on my class is extremely simple. It just sets a value on the _options array based on the key and value passed to it.
The last method I’m going to show you is __call. And this one gets invoked whenever a script attempts to access a method that hasn’t been defined or at least hasn’t been declared as public. It accepts 2 arguments – the name of the method requested, and the arguments that the calling script tried to pass to it. The second argument, in this case, is an array.
Now, my class doesn’t define any non-magic methods, but it does have a private property called _helper. _helper is an instance of the Helper class, and that class does define public methods. Well, it defines one anyway.
{show code sample}
So, what I decided to do in my __call method
{show code sample}
is to check to see whether or not the _helper object has a method with the same name as the one that the calling script tried to access, and if it does, it will call that method with the same arguments that were used when the script tried to access it.
Now, if you know your design patterns, you’ll recognize that this a handy technique in case you want to use the Bridge pattern. And actually, I also want to call your attention to the nifty PHP function here ‘call_user_func_array’. In these videos, I make no effort to try and cover all the useful built-in functions PHP comes loaded with (there’s just too many), but this is a pretty cool one. When I call it this way like you see here, it actually acts exactly as though I had called this method here with these arguments, even though they’re variables. That means there’s no performance penalty the way you’d expect if you tried to mimic this exact same functionality using an eval statement. So if you aren’t already familiar with it, I recommend learning about this function and all the different ways it can be invoked. Look it up in the PHP manual when you have a chance.
Back to the topic at hand though, now that I’ve introduced you to these four methods, let’s take a look at some sample code to see them in action.
{show sample code}
Here you see I’m going to create a new instance of my Magical class. Then, I’m going to set a property named ‘two’ with an array, but of course, since my class doesn’t define a property called ‘two’ it’ll have to invoke the ‘__set’ magic method. Next I’m going to retrieve that property, and use var_export to display it on the screen, which means PHP will also have to invoke my __get magic method.
{switch to output}
And there, sure enough, you see the message “I was constructed” coming out of the constructor, and there below it is the exported array. So we know the first 3 methods worked.
{switch to code}
Lastly, I’m going to place a call to a method named ‘doSomething’ which doesn’t actually have a definition in the Magical class, but does have a definition on the Helper class, and you’ll see the output from that.
{switch to output}
And that right there is the correct output based on the arguments I passed.
Now, the line ‘Good-bye’ at the end of the script probably looks a little strange. But it’s there for a good reason. The class ‘Magical’ actually defines all 14 magic methods, and just like there’s one that gets invoked when an object is created, there’s one that gets invoked when an object gets destroyed. In this case, all it does is print out that message ‘Good-bye’. If you’re interested, I invite you to check out the Magical class in the files included with this lesson. There you’ll see at least 10 other methods I didn’t talk about, and if you want to learn even more, just search the PHP manual for “magic methods”.
{show website}
I should mention before I wrap up, that __call has a static analog called __callStatic. It gets invoked when you try to call a static method on a class that hasn’t been declared, or else isn’t declared public. And also, at the time I’m recording this, a change request has been approved by the PHP engineers to incorporate a __getStatic and __setStatic pair of methods as well. Depending on how old these videos are, those methods might be available to you today. I’d use them in some of my scripts right now if I could. As it is, there’s no way to avoid a fatal error if you try to access an undeclared static property.
January 21 2010 | PHP tutorial scripts | Comments Off on An introduction to magic methods
« Prev - Next »