Last active
October 21, 2021 10:44
-
-
Save AnrDaemon/d2e03388da9ff48cefa0d88c08bf9da9 to your computer and use it in GitHub Desktop.
Domain to infrastructure chained API interaction
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 | |
/** Wrapper for actual thing that do the network talking. | |
This could be encapsulation for curl, Guzzle, Net\Browser, etc. | |
The wrapper offers a known stable interface to external library. | |
*/ | |
class Service\Api\Wrapper | |
{ | |
} | |
/** The service connector that knows how to invoke methods of remote API. | |
It only knows how to map API method calls to the wrapper, but have no idea | |
of any API methods existence. | |
*/ | |
class Service\Api\Connector | |
{ | |
function get(...$stuff); // The "get stuff" method | |
function exec(...$stuff); // The "change stuff" method | |
function __construct(Service\Api\Wrapper $api); | |
} | |
/** The Domain API client is the in-program representation of the API | |
It "knows" the API methods, their parameters and such. | |
*/ | |
class Domain\Api\Client | |
{ | |
protected $connector; | |
/** Service method to associate API methods with handlers | |
The $callHandler can be either a class name or an object. | |
In either case, the resulting object should provide '__apiCall' "magic" method. | |
*/ | |
function setCallerClass($callName, $callHandler) | |
{ | |
$this->overrides[$callName] = $callHandler; | |
} | |
/** The "method handler" function | |
The PHP's "magic" '__call' function is invoked for undefined/inaccessible class methods. | |
'$name' should be a previously assigned $callName or a class name in the Domain\Api\Calls\* namespace. | |
*/ | |
function __call($name, $params) | |
{ | |
if(isset($this->overrides[$name])) | |
{ | |
$caller = $this->overrides[$name]; | |
} | |
else | |
{ | |
$caller = "Domain\\Api\\Calls\\{$name}"; | |
} | |
if(!is_object($caller)) | |
{ | |
$caller = new $caller($this->connector); | |
} | |
$result = $caller->__apiCall(...$params); | |
return $result; | |
} | |
function __construct(Service\Api\Connector $api) | |
{ | |
$this->connector = $api; | |
} | |
} | |
class Domain\Api\Calls\GetStuff | |
{ | |
protected $connector; | |
function __apiCall(...$params) | |
{ | |
return $this->connector->get(...$params); | |
} | |
function __construct(Service\Api\Connector $api) | |
{ | |
$this->connector = $api; | |
} | |
} | |
// ... | |
$client = new Domain\Api\Client($connector); | |
$stuff = $client->GetStuff($some, $stuff); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment