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); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Glad you like it. I just tried it in PHP. This should work in 5.3 and above.
There is no partial application because
vsprintf
doesn't seem to support it.