Last active
December 29, 2015 18:19
-
-
Save devster/7710264 to your computer and use it in GitHub Desktop.
Elegant way to create an API URL
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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); | |
} |
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!
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
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.
Try it here: http://codepen.io/FWeinb/pen/bc3b819b32edfe82fd67492002c7fc32 ( open dev tools)