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.

Resources<br />

A resource is a generic data container that can hold any sort of data. An internal list<br />

mechanism keeps track of your resources, which are referenced through simple<br />

resource identifiers.<br />

Use resources in your extensions when the extension is providing an interface to<br />

something that needs cleanup. When the resource goes out of scope or your script<br />

ends, your destructor function for that resource is called, and you can free memory,<br />

close network connections, remove temporary files, etc.<br />

Here’s a simple little example where we tie our resource to a trivial struct that contains<br />

only a string and an integer (name and age, in this case):<br />

static int le_test;<br />

typedef struct _test_le_struct {<br />

char *name;<br />

long age;<br />

} test_le_struct;<br />

The struct can contain anything: a file pointer, a database connection handle, etc.<br />

The destructor function for our resource looks like this:<br />

static void _php_free_test(zend_rsrc_list_entry *rsrc TSRMLS_DC) {<br />

test_le_struct *test_struct = (test_le_struct *)rsrc->ptr;<br />

efree(test_struct->name);<br />

efree(test_struct);<br />

}<br />

In your MINIT( ) function, add this line to register your destructor for the le_test<br />

resource:<br />

le_test = zend_register_list_destructors_ex(_php_free_test, NULL, "test",<br />

module_number);<br />

Now, here’s a fictitious my_init( ) function that initializes the data associated with<br />

the resource. It takes a string and an integer (name and age):<br />

<strong>PHP</strong>_FUNCTION(my_init) {<br />

char *name = NULL;<br />

int name_len, age;<br />

test_le_struct *test_struct;<br />

}<br />

if (zend_parse_parameters(ZEND_NUM_ARGS( ) TSRMLS_CC, "sl", &name,<br />

&name_len, &age) == FAILURE) {<br />

return;<br />

}<br />

test_struct = emalloc(sizeof(test_le_struct));<br />

test_struct->name = estrndup(name, name_len);<br />

test_struct->age = age;<br />

ZEND_REGISTER_RESOURCE(return_value, test_struct, le_test);<br />

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

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

Resources | 349

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

Saved successfully!

Ooh no, something went wrong!