* @license http://creativecommons.org/licenses/by/3.0/ CC-BY 3.0 * @see http://www.shesek.info/php/generic-php-object-wrapper-for-resources */ class ResourceWrapper { /** * POS_FIRST and POS_LAST are used to set the correct position of the * resource argument on function calls. */ const POS_FIRST = 1; const POS_LAST = 2; /** * Holds the PHP resource being wrapped * * @var resource */ protected $resource; /** * The prefix for functions related to this resource * * e.g. 'image' for GD, 'mysql_' for mysql, 'bz' for bzip, etc * * @var string */ protected $prefix; /** * The position of the resource argument on function calls * * Either ResourceWrapper::POS_FIRST or ResourceWrapper::POS_LAST * * @var integer */ protected $resource_position = 1; /** * The constructor creates the PHP resource and stores it locally on the object. * * The $prefix and $method arguments are used to determine the function name, * and the rest of the arguments are passed untouced to it. * * For example, passing 'mysql_' as the $prefix and 'connect' as the $method * would cause it to call mysql_connect(), with the other parameters. * * new ResourceWrapper('mysql_', 'connect', 'localhost', 'nadav') * is translated to mysql_connect('localhost', 'nadav') * * @param string $prefix * @param string $method */ public function __construct($prefix, $method) { $this->prefix = $prefix; $args = func_get_args(); $this->resource = $this->__call($method, array_slice($args, 2)); } /** * Delegates calls to the original PHP functions while passing the resource. * * Adds the function prefix (as defined in the constructor) to the method name * being called, passes the resource along with the other arguments, invokes * the original function and return the return value from it. * * @param string $method * @param array $args * @return mixed */ public function __call($method, $args) { if (!is_null($this->resource)) { if ($this->resource_position === self::POS_FIRST) { array_unshift($args, $this->resource); } else { array_push($args, $this->resource); } } return call_user_func_array($this->prefix . $method, $args); } /** * Set wheter the resource should be passed last or first in the arguments. * * @param integer $position ResourceWrapper::POS_FIRST or ResourceWrapper::POS_LAST */ public function _setPosition($position) { $this->resource_position = $position; return $this; } /** * Returns the wrapped PHP resource. * * @return resource */ public function _getResource() { return $this->resource; } /** * Magic toString conversion */ public function __toString() { return 'ResourceWrapper for '.get_resource_type($this->resource); } }