Archive for the ‘PHP’ Category

No require with autoload

2. January 2011

No Comments »

If you have ever worked with a PHP framework you probably have noticed some features that allow you to develop code more rapidly. In this blog, I am going to address autoloading.

Traditionally, in object oriented PHP, we create a new source file for each class. If we want to create an object of a class, we have to include the php file using require_once (or using a similar function). If we do not include the source file, we will be issued a fatal error.

Fatal error: Class 'User' not found in ...

Lets say we have a User class defined as follows in a User.php file

[code lang="PHP"]

class User {
function __construct() {
echo "Hello, World!";
}
}
?>[/code]

If we want to create a new User object we would include user.php and use the new keyword to instantiate the class.

[code lang="PHP"] require_once('user.php');
$user = new User();[/code]

This is method reasonable for a small number of classes. However, large frameworks can span hundreds of classes, and having to write require_once for each class becomes a huge annoyance. PHP5 introduced an autoload magic method which is automatically called if the class source file cannot be found. The __autoload function takes a single parameter - the class being instantiated. If our class name corresponds to its file name we can do something as simple as:

[code lang="PHP"] function __autoload($class) {
require_once($class . ".php");
}[/code]

Now, each time you instantiate a class, the autoload function will be automatically ran and it will automagically require your class. This is great, however all classes have to be in the same directory as the callee, and any decent framework uses a class hierarchy and spreads classes out into different directories. When I was writing my framework a few years ago, I stumbled upon a pretty awesome use of the autoload function. I think the idea was borrowed from the Zend framework. In a nutshell, the class names would correspond to their location on the file system. For example, the Zend framework has a class named Zend_Controller_Action_HelperBroker, and the class path Zend/Controller/Action/HelperBroker.php. What does this mean? With some additional code in our autoload function, we can convert the class name into its respective path allowing use to create a class hierarchy on our file system.

[code lang="PHP"] function __autoload($class) {
$file = str_replace("_", "/", $class);
require_once($file . ".php");
}[/code]

Now, with the onset of PHP5.3 and the introduction of namespaces, this method has been kind of depreciated for a more pragmatic method. Instead of naming our classes with really long names that correspond to their path, we can use a namespace instead. Thus our autoload function would look like:

[code lang="PHP"] function __autoload($class) {
$file = str_replace("\\", "/", $class);
require_once($file . ".php");
}[/code]

In my next blog, I will talk more about namespaces and give a better demo on how this is used.

Sending Text Messages in PHP

7. August 2010

3 Comments »

Recently I’ve had to implement an alert system in PHP were the alerts are sent via a text message. The concept is very simple – use an email to SMS gateway. Essentially, you send an email to a phone companies gateway server, that server then relays the email to the phone number specified via a SMS. Since PHP has the ability to send emails, the whole process is quite easy.

1. First you need to acquire a list of SMS gateways you are going to support. For an extensive list, check out Wikipedias List of SMS Gateways. For this tutorial, I will only be using AT&T Wireless (number@txt.att.net) and Verison (number@vtext.com).

2. Create a simple HTML form.
[code lang="html"]



[/code]

3. Add the necessary PHP code to send the email
[code lang="PHP"]



if(!empty($_POST['number'])) {
mail($_POST['number'] . $_POST['provider'], $_POST['subject'], $_POST['message']);
}
?>


[/code]

You will want to do some better error checking and validation, but thats it!

Grayscale Images with GD

18. January 2010

2 Comments »

In computing, a grayscale or greyscale digital image is an image in which the value of each pixel is a single sample, that is, it carries the full (and only) information about its intensity. Images of this sort are composed exclusively of shades of neutral gray, varying from black at the weakest intensity to white at the strongest.

In PHP, it is easy enough to do. First we want to create two image resources. First we need our original image so we can map its color. Second we need to create an image which will become our grayscale image.

[code lang="php"] //change this to your image location
$original = @imagecreatefrompng("/home/john/Documents/colorized.png")
or die("Cannot Initialize new GD image stream");

$im = @imagecreate(imagesx($original), imagesy($original))
or die("Cannot Initialize new GD image stream");
[/code]

Next we want to create our color pallet. Since we our goal is a gray image,we will only use shades of black and white. Colorized images are generally within the RGB color space. Meaning each pixel is composed of red, green, and blue light which allows you to reproduce a broad array of colors. White is represented as 255,255,255 and black is represented as 0,0,0. Therefore, all gray shades are represented as x,x,x. So we thus create our pallet:
[code lang="php"] for ($i = 0; $i <= 255; $i++) {
$palette[$i] = imagecolorallocate($im, $i, $i, $i);
}[/code]

Next we want to create a function to convert from the RGB color space to some color space that only represents the pixels intensity. The YIQ is the best color space for this since the Y represents the luma of the pixel. The numbers I use in the function below comes from the Y component: YIQ - Wikipedia, the free encyclopedia
[code lang="php"] function grayscale($r, $g, $b) {
return 0.299*$r + 0.587*$g + 0.114*$b;
}[/code]

Now we actually need to get the RGB values of each pixel so we can convert if. To do this, we iterate over the entire image (so large images will take some time), and place the transformed pixel onto the new image we wish to create.

[code lang="php"] for($x = 0; $x < imagesx($original); $x++) {
for($y = 0; $y < imagesy($original); $y++) {
$rgb = imagecolorat($original, $x, $y);
$r = ($rgb >> 16) & 0xFF;
$g = ($rgb >> 8) & 0xFF;
$b = $rgb & 0xFF;
imagesetpixel($im, $x, $y, $palette[grayscale($r, $g, $b)]);
}
}[/code]

Now all that is left is to set the header and create the image. The final code is below.

[code lang="php"] header("Content-type: image/png");

$original = @imagecreatefrompng("/home/john/Documents/colorized.png")
or die("Cannot Initialize new GD image stream");

$im = @imagecreate(imagesx($original), imagesy($original))
or die("Cannot Initialize new GD image stream");

for ($i = 0; $i <= 255; $i++) {
$palette[$i] = imagecolorallocate($im, $i, $i, $i);
}

function grayscale($r, $g, $b) {
return 0.299*$r + 0.587*$g + 0.114*$b;
}

for($x = 0; $x < imagesx($original); $x++) {
for($y = 0; $y < imagesy($original); $y++) {
$rgb = imagecolorat($original, $x, $y);
$r = ($rgb >> 16) & 0xFF;
$g = ($rgb >> 8) & 0xFF;
$b = $rgb & 0xFF;
imagesetpixel($im, $x, $y, $palette[grayscale($r, $g, $b)]);
}
}

imagepng($im);
imagedestroy($im);
?>[/code]

Attached is an example of a colorized image (left) and the same image using the above code (right)