Skip to content

Instantly share code, notes, and snippets.

@phpfiddle
Created July 20, 2017 16:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save phpfiddle/a874a6f751d4505d1d5ab71340591b44 to your computer and use it in GitHub Desktop.
Save phpfiddle/a874a6f751d4505d1d5ab71340591b44 to your computer and use it in GitHub Desktop.
[ Posted by Aleksandar Puharic ] Example usage of interfaces in API clients classes. Doesn't communicate with actual API server but just tries to simulate the process. In reality, interface and implementing class should be in separate files with respective filenames and paths.
<?php
namespace InterfacesExampleApi;
/**
* Interface ApiClientInterface
* @package InterfacesExampleApi
*/
interface ApiClientInterface
{
/**
* @param string $username
* @param string $password
* @return mixed
*/
public function createUser(string $username, string $password);
/**
* login user with created token
*
* @param string $username
* @param string $password
* @param string $token
* @return mixed
*/
public function loginUser(string $username, string $password, string $token);
/**
* Logout user via token
*
* @param string $token
* @return mixed
*/
public function logoutUser(string $token);
}
/**
* Class ApiClient
* @package InterfacesExampleApi
*/
class ApiClient implements ApiClientInterface
{
/**
* @var string
*/
protected $apiServer;
public function __construct(string $apiServer)
{
$this->apiServer = $apiServer;
}
/**
* @param array $params
*/
protected function apiCall(array $params)
{
return "Simulated: Sent {$params['action']} API call to {$this->apiServer}." . PHP_EOL . " Request: " . PHP_EOL . json_encode($params['params'], JSON_PRETTY_PRINT) . PHP_EOL . PHP_EOL;
}
public function createUser(string $username, string $password)
{
return $this->apiCall([
'action' => __FUNCTION__,
'params' => [
'username' => $username,
'password' => crypt($password, 'superSecretSalt123')
]
]);
}
public function loginUser(string $username, string $password, string $token)
{
return $this->apiCall([
'action' => __FUNCTION__,
'params' => [
'username' => $username,
'password' => $password,
'token' => $token
]
]);
}
public function logoutUser(string $token)
{
return $this->apiCall([
'action' => __FUNCTION__,
'params' => [
'token' => $token
]
]);
}
}
$api = new ApiClient("https://api.example.io");
$token = bin2hex(random_bytes(32));
echo "<pre>";
echo $api->createUser("JohnSmith", "smith1234");
echo $api->loginUser("JohnSmith", "smith1234", $token);
echo $api->logoutUser($token);
echo "</pre>";
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment