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);
}
@FWeinb
Copy link

FWeinb commented Dec 1, 2013

Nice solution. I made a Javascript equivalent to this. Made a few changes to it. The getRessourceFunction will return a new function which than can be used to generate URLs. Don't know if this is possible in PHP.

/**
 * Javascript Solution
 * 
 * Usage:
 *  
 *   var getProductRessource = getRessourceFunction('/product/%s/id-%s');
 *  
 *        getProductRessource('edit', 13) // will return "/product/edit/id-13"
 *  
 * Supports simple partial application like: 
 *
 *  var getPageRessource = getRessourceFunction('/page/%s/%s');
 *     
 *       getPageRessource('news', 1)); // "/page/news/1"
 *
 * or 
 *
 *       getPageRessource('news') // "/page/news"
 * 
 */
function getRessourceFunction ( patternString ) {
  var pattern = patternString.split(/\%s/);
  return function (/* params */){
    var res    = '', length = arguments.length;
    for ( var i=0;i<length;i++){
      res += pattern[i] + arguments[i];
    }
    return res;
  }
}

Try it here: http://codepen.io/FWeinb/pen/bc3b819b32edfe82fd67492002c7fc32 ( open dev tools)

@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