05.05.2013 Views

Programming PHP

Programming PHP

Programming PHP

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 14 CHAPTER 14<br />

Extending <strong>PHP</strong><br />

This chapter shows you how to write C language extensions to <strong>PHP</strong>. Although most<br />

functionality can be written in the <strong>PHP</strong> language, sometimes you need the extra<br />

speed and control you get from the C API. C code runs an order of magnitude faster<br />

than most interpreted script code, and it is also the mechanism for creating the thin<br />

middle layer between <strong>PHP</strong> and any third-party C library.<br />

For example, to be able to talk to the MySQL database server, <strong>PHP</strong> needs to implement<br />

the MySQL socket protocol. It would be a lot of work to figure out this protocol<br />

and talk to MySQL directly using fsockopen( ) and fputs( ) from a <strong>PHP</strong> script.<br />

Instead, the same goal can be accomplished with a thin layer of functions written in<br />

C that translate MySQL’s C API, implemented in the libmysqlclient.so library<br />

included in MySQL, into <strong>PHP</strong> language-level function calls. This thin layer of functions<br />

is known as a <strong>PHP</strong> extension. <strong>PHP</strong> extensions do not always have to be a layer<br />

between <strong>PHP</strong> and some third-party library, however. An extension can instead completely<br />

implement some feature directly (for example, the FTP extension).<br />

Before we get into the details of writing extensions, a note of caution. If you are just<br />

learning <strong>PHP</strong> and do not have any sort of C programming background, you should<br />

probably skip this chapter. Extension writing is an advanced topic, and it is not for<br />

the faint of heart.<br />

Architectural Overview<br />

There are two kinds of extensions that you can write: <strong>PHP</strong> extensions and Zend<br />

extensions. We will focus on <strong>PHP</strong> extensions here. Zend extensions are lower-level<br />

extensions that somehow modify the very core of the language. Opcode cache systems<br />

such as APC, Bware afterBurner, and ZendCache are Zend extensions. <strong>PHP</strong><br />

extensions simply provide functions or objects to <strong>PHP</strong> scripts. MySQL, Oracle,<br />

LDAP, SNMP, EXIF, GD, and ming are all examples of <strong>PHP</strong> extensions.<br />

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

Copyright © 2002 O’Reilly & Associates, Inc. All rights reserved.<br />

317

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

Saved successfully!

Ooh no, something went wrong!