21.6 Creating Resource Identifiers


You want to create a resource identifier; that is, something such as a file pointer or a database handle.

Technique

There are a couple of steps and conventions, so let me walk you through the process.

  1. First, create a variable in the global structure (of your module for thread safety) and name it le_YOURNAME (naming conventions are not required, but that's how everyone else does it):

     typedef struct {     int le_YOURNAME; } php_YOURNAME_globals; 
  2. Create a function that you want to execute when the script finishes its execution:

     /* Completely fictional function */ static void _php_MODULENAME_close(handle *ha) {     close_handle(ha); } 
  3. If you have something you want to do with that resource identifier on either startup or shutdown, place that information in PHP_MINIT_FUNCTION() (a function that is called on module startup):

     PHP_MINIT_FUNCTION(modulename) {     YOURMODLS_FETCH(); graphics/three.gif YOURMODG(le_YOURNAME) = register_list_destructors(php_MODULENAME_close,                                                           NULL);     return SUCCESS; } 
  4. When the time comes, register that resource:

     PHP_FUNCTION(open) {     zval **filename;     YOURMODLS_FETCH():     if (ZEND_NUM_ARGS() != 1          zend_get_parameters_ex(1, &filename) == FAILURE) {         WRONG_PARAM_COUNT;     }     convert_to_string_ex(filename);     Handle *h = openhandle(Z_STRVAL_PP(filename));     ZEND_REGISTER_RESOURCE(return_value, h, YOURMODG(le_YOURNAME)); } 
  5. You just created a resource.

Comments

A resource indicator is something like the file handle you pass to fwrite() or the connection handle that a database returns when you connect to it. In PHP, you can use the preceding steps to create a resource indicator. For information on how to manage this resource indicator, see recipe 21.5.

The ZEND_REGISTER_RESOURCE macro will insert your resource into the resource table and then place its corresponding resource identifier in the first argument (in this case, the function's return value).

The register_list_destructors() function registers a function (given by the first argument) to be executed when the script finishes execution. This ensures that you don't have resource identifiers lying around when your script closes if your user doesn't manually free the resources.

The ZEND_REGISTER_RESOURCE() macro is really a placeholder for the following code:

 ZVAL_RESOURCE(return_value, zend_list_insert(h, YOURMODG(le_YOURNAME)); 


PHP Developer's Cookbook
PHP Developers Cookbook (2nd Edition)
ISBN: 0672323257
EAN: 2147483647
Year: 2000
Pages: 351

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net