Archive for the ‘PHP’ category

My beloved programming language and all things concerning it - the scripts I've written, the tutorials I've prepared and the problem solutions I've found.

OOP in PHP (part II)

Sunday, December 16th, 2007

Time to discover the hidden powers of the object oriented programming in PHP. Today I’ll describe the usage of serialisation, the secrets of overloading and - probably the most useful thing today - design patterns.

Serialisation

As you remember from the first part of the article, objects are completely different type of variables. You could easily write a string, number or even an array to a file… but what about objects? You can’t just write an object to a file, as PHP will try to convert it to a string, which is technically impossible, and will result in throwing an error. Yeah, I guess you can already suppose that there’s a solution.

Actually, all you have to do to serialise an object (i.e. make it writable to a file) is use one function: serialize(). As you can guess, using unserialize() function will allow you to have your object back once it has been saved to a file. Remember to define the object’s class before unserialising it, otherwise it will become useless.

Methods __sleep() and __wakeup() make serialisation in PHP5 even easier. They are called, respectively, before an object is serialised or unserialised. They are very useful e.g. for closing and reopening database connections, or saving additional information about the serialisation process. Remember that the __sleep() magic function has to return an array of all members that should be serialised.

class AutoStalker {
   private $filename, $file;

   public function __construct($filename) {
      $this->filename = $filename;
      $this->open();
   }

   public function prepare_for_stalking() {
      $this->file = fopen($this->filename, 'a');
   }

   public function stalk($text) {
      fwrite($this->file, $text."\n");
   }

   public function see_whos_been_stalked() {
      return file_get_contents($this->filename);
   }

   public function __wakeup() {
      $this->prepare_for_stalking();
   }

   public function __sleep() {
      fclose($this->file);
      return array('filename');
   }
}

In the example above, I only serialise the file’s name, because we don’t need any additional information to open that file in the future.
Now, let’s see something more useful; how about using some PHP cookies?

(more…)

OOP in PHP

Sunday, October 14th, 2007

It’s been a long time since my last post. Sorry for this to all of you who have been looking forward to my next article (yeah, both of you!).

I do like functions. I even try to use functions instead of classes wherever it’s possible - either it’s just because I got used to it by writing PHP for two years (as coding object oriented scripts in PHP 4 was actually impossible), or I’m too stupid to understand the real power of OOP. And even though PHP’s authors have been trying to implement a nice object structure, it still sucks. However, as I consider PHP to be the nicest programming language, I decided to describe its OOP powers.

Why?

Let’s start with the definition of OOP: by using objects, it allows you to keep your code clean and prepared for further development. I suppose you still don’t know what an object is. Think about this: you create a function, let’s call it omg_am_i_pregnant($user), that will check whether the user is pregnant. It actually can return some data, but it’s very difficult to reuse it afterwards. It would probably look like this:

function omg_am_i_pregnant($user) {
   if (user_exists($user) && is_pregnant($user)) {
      $p = true;
   }
}

By doing the same thing with a class called pregnancy, you can easily store the data and send it to, let’s say, a sperm bank.


class Pregnancy {
   function __construct($user) {
      if (user_exists($user) && is_pregnant($user)) {
         $this->p = true;
      }
   }
}

Now, you may think “WTF are you talking about, the second piece of code is longer and does the same thing”. Yeah, but now, let’s try to check whether Anne, Isabelle and Lucy are pregnant and store the data simultaneously.

$anne = omg_am_i_pregnant('Anne');
$isabelle = omg_am_i_pregnant('Isabelle');
$lucy = omg_am_i_pregnant('Lucy');

The code above won’t work properly, as the function saves the result to the $p variable. Of course, this could be done many other ways, but what if you had to do it this way, using $p?

(more…)

PHP can do graphics, too!

Monday, August 6th, 2007

Yeah, I still like PHP. All the drawbacks haven’t really convinced me to stop writing in PHP, as they all will be corrected either in the next updates of PHP 5 or in the forthcoming PHP 6. That’s why, despite many people saying “stp wrting php, u n00b!“, I still want to use this language and I still want to share my knowledge ;) So I decided to write a short tutorial explaining how to generate images using PHP.

Introduction

Among many PHP graphic extensions, two are the most functional: GD and Imlib2. However, only the former will be described here, as Imlib2 actually sucks. And so, you’ll have to check whether your server supports GD. Create a file where you call the function phpinfo(), open it and find the GD section. The table shows if GD is enabled on your server (if it isn’t, go to official GD site and download it or contact your admin) and what file types it supports.

Now that you’re sure that your server can actually do all the things mentioned in this post, let’s continue with it. But before we can get into the image generation, I have to make sure you take one thing into consideration: a site consisting of some text and two images sends three HTTP requests to the server. Each image makes the server process one more request, as it’s content type is other than the site’s (images use e.g. image/png type, whereas the whole pages use text/html or application/xhtml+xml). And so you must remember that you can’t print text and images within the same PHP file, as it will cause errors.

Let’s start with some simple image generation. First, we’ll use some simple GD colouring and drawing functions. ImageCreate(width, height) creates an image. Then, we’ll define some colours and assign them to variables with ImageColorAllocate(image, red, green, blue) and finally we’ll create a red rectangle using the ImageFilledRectangle(image, top_left_x, top_left_y, bottom_right_x, bottom_right_y, colour) function (its arguments are the top left and bottom right points’ coordinates). Next, we’ll have to send the header() to the server to tell it that the file’s an image, not text. Eventually, we’ll use a the ImagePNG(image [, filename]) creating the actual image.

<?php
$image = ImageCreate(150, 150);
$white = ImageColorAllocate($image, 255, 255, 255);
$red = ImageColorAllocate($image, 255, 0, 0);
ImageFilledRectangle($image, 50, 50, 150, 150, $red);
header('Content-Type: image/png');
ImagePNG($image);
?>

(more…)

Cyanide and Happiness

Friday, July 27th, 2007

Unfortunately, the boredom mentioned in the previous post hasn’t gone away and I had enough time to write another PHP script for comics displaying. This time it’s about Cyanide and Happiness, one of the funniest web comics on the Web.

The Lol! Fag!! superhero from C&HIt was much more difficult to write this script, because the comic isn’t categorised by date nor are its image files. I had to use cURL and even get the latest strip’s number from the C&H’s feed (although accessing explosm.net/comics redirects you to the latest one, it’s impossible to do such thing with cURL). It’s quite more complicated than the Garfield script and it (unluckily) takes more time to load. Also, because of the C&H authors’ carelessness, there are some gaps between episodes (e.g. after episode 15, there’s a huge gap until episode 39). I hard-coded a solution for one gap only, hope you won’t find it very annoying (the script displays an error message if there’s no strip with the requested number). The script has similar functionality to the Garfield one - it displays all kind of possible errors, has a simple yet sufficient menu.

All feedback is welcome, although - as with my previous ‘comic script’ - I’d prefer not develop this script, everything’s in your hands.

Enjoy. Here’s a working example, and the source code.

Garfield

Thursday, July 26th, 2007

Garfield
Summer. The hottest and the most boring time of the year. There’s literally nothing to do, so I decided to read all Garfield’s episodes. After an hour I found it extremely boring, and then I got another great idea: let’s write a script allowing you to show some Garfield’s episodes on your page.

And here you are. It allows you to display an episode of Jim Davis’ comic for any day since 19 June 1978, displays error messages when you do something wrong (enter the date in a wrong format, enter a date before 19 June 1978, enter a date after today). It displays links to get to the previous or next comic, as well as a small form to enter a requested date. If you want to display a random strip, enter the script with $_GET['date'] set to ‘random’ (e.g. garfield.php?date=random).

Hope you enjoy it and maybe make something useful with it (e.g. write some kind of plugin for a social networking site?). I don’t really want to develop the script futher, so I leave it all to you. I even release the script under no license - if you want, you can show it off to your friends saying that you made it all by yourself.

If the boredom won’t leave me alone, maybe I’ll write some other scripts like this. But I really hope I won’t be forced to do so.
Have fun with the Garfield’s PHP script. Here’s a working example, and the source code.