Skip to content

Instantly share code, notes, and snippets.

@devster
Last active December 29, 2015 18:19
Show Gist options
  • Save devster/7710264 to your computer and use it in GitHub Desktop.
Save devster/7710264 to your computer and use it in GitHub Desktop.
Elegant way to create an API URL
<?php
/**
* Elegant way to create an API URL
*
* Usage:
* $this->getResourceUrl('/product/%s/id-%d', 'edit', 13);
* // will produce http://domain.com/product/edit/id-13
*
* // A resource can be an array to embed this method in an other method
* public function anotherMethod($resource, $data)
* {
* // and resource is ['/product/%s/id-%d', 'edit', 13]
* $url = $this->getResourceUrl($resource)
* }
*
* // Also a resource can be just a simple string '/products'
*/
protected function getResourceUrl()
{
$args = func_get_args();
$resource = array_shift($args);
if (is_array($resource)) {
$args = $resource;
$resource = array_shift($args);
}
return $this->apiRestUrl . vsprintf($resource, $args);
}
@devster
Copy link
Author

devster commented Dec 1, 2013

Yes its possible in PHP with the Closure system (anonymous functions!), I'll check if it is relevant to do this in PHP. Thanks for your idea!

@FWeinb
Copy link

FWeinb commented Dec 1, 2013

Glad you like it. I just tried it in PHP. This should work in 5.3 and above.

<?php
  function getResourceFunction ( $resource ){
      return function() use ($resource){
        return vsprintf($resource, func_get_args());
      };
  };

  $getProductRessource = getResourceFunction ( '/product/%s/id-%s' );


  echo $getProductRessource ( 'edit', 13 );
?>

There is no partial application because vsprintf doesn't seem to support it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment