Archive for the ‘Tutorial’ 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…)

[siː dʒiː aɪ]

Tuesday, August 14th, 2007

Note: if you can’t see the title, it means your browser can’t display Unicode characters properly.

The Common Gateway Interface (CGI) is a standard protocol for interfacing external application software with an information server, commonly a web server. This allows the server to pass requests from a client web browser to the external application. The web server can then return the output from the application to the web browser.

Wikipedia

Today, I’ll explain how to generate Web pages using Python - the easiest programming language ever. They won’t be just static pages, however; in the article there will be examples of CGI scripts processing data from HTML forms, uploading files to the server, some GET and POST requests and even a simple how-to showing how to set up a small CGI server. However, this article is about using CGI in Python, so I assume you have some knowledge of the Python syntax.

The simpliest of the simpliest

Let’s start with a simple static page. The first line of any CGI script has to point to the location of Python. It’ll usually be /usr/bin/python on most Unix-based servers. Next, we have to inform Python that the output of the script is actually HTML (and put an \n at the end of this line)- and the rest of the code is up to you. Remember that all CGI scripts need permissions at least equal to chmod 755.

#!/usr/bin/python
print "Content-type: text/html\\n"
print "OMG, it's actually working!"

You can see the script working.
Of course, this script doesn’t even include the most basic html tags such as <html> and <body>, so have a look at a second example:

#!/usr/bin/python
print "Content-type: text/html\\n"
print """<html>
<head>
<title>OMG</title>
</head>
<body>
<h2>It's actually working!</h2>
<img src="some_crappy_image_source">
</body>
</html>"""

Again, you can see how it works.

(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…)