05.05.2013 Views

Programming PHP

Programming PHP

Programming PHP

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

This will put a php binary in your /usr/local/bin directory. The configure line above<br />

adds MySQL, PostgreSQL, and zlib support. While you don’t need them to develop<br />

your extension, they won’t get in the way, and it is a good idea to have a php binary<br />

that can run complex web applications directly from the command line.<br />

Just to make sure it worked, test it:<br />

% /usr/local/bin/php -v<br />

4.2.0-dev<br />

Planning Your Extension<br />

As much as you probably just want to dive in and start coding, a little bit of planning<br />

ahead of time can save you a lot of time and headaches later. The best way to<br />

plan your extension is to write a sample <strong>PHP</strong> script that shows exactly how you plan<br />

to use it. This will determine the functions you need to implement and their arguments<br />

and return values.<br />

For example, take a fictitious rot13 * extension that might be used as follows:<br />

<br />

From this we see that we need to implement a single function, which takes a string as<br />

an argument and returns a string. Don’t let the simplicity of the example fool you—<br />

the approach we’ll take holds for extensions of any complexity.<br />

Creating a Skeleton Extension<br />

Once you have planned your extension, you can build a skeleton with the ext_skel<br />

tool. This program takes a .def file, which describes the functions your extension will<br />

provide. For our example, rot13.def looks like this:<br />

string rot13(string arg) Returns the rot13 version of arg<br />

This defines a function that returns a string and takes a string argument. Anything<br />

after the close parenthesis is a one-line description of the function.<br />

The other types valid in a .def file are:<br />

void<br />

For functions that return nothing or take no arguments<br />

bool<br />

Boolean<br />

* rot13 is a simple encryption algorithm that rotates the English alphabet by half its length. “a” becomes “n”<br />

and “z” becomes “m,” for example.<br />

320 | Chapter 14: Extending <strong>PHP</strong><br />

This is the Title of the Book, eMatter Edition<br />

Copyright © 2002 O’Reilly & Associates, Inc. All rights reserved.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!