I implemented an Auth
class in PHP responsible for authenticating with the (external domain) API, apart from my API
class which is responsible for doing all the normal POST requests to this API.
The class Auth works as such:
class Auth {
private $api;
public function __construct() {
$this->api = new API;
}
public function handleSession() {
if (!isset($_SESSION)) {
session_start();
}
if (!isset($_SESSION["ACCESS_TOKEN"])) {
$_SESSION["REFERER"] = $_SERVER["PHP_SELF"];
header("Location: auth.php");
exit;
} else {
unset($_SESSION["REFERER"]);
}
}
}
It uses dependency injection with an API instance.
There are other methods that access private API attributes through accessors, such $this->api->getAttr();
.
At the start of every page the client accesses, I use the following at the start of the page to check if a token is established to proceed. If not, it will redirect to auth.php and start the authentication process.
$api_auth = new Auth();
$api_auth->handleSession();
However, I want to change it to the following cleaner way, so whenever I'm dealing with this api, I simply instantiate API and can access Auth from it, as such:
$api = new API();
$api->auth->handleSession();
To add an Auth instance in the constructor of API, so it would be more encapsulated, however I couldn't really think about how to achieve this, since Auth would still need to access API attributes to actually authenticate.
I tried adding arguments to Auth methods and also implement them in API:
class Auth {
// ...
public function makeRequest($id, $attr) {
// make request to api
}
// ...
}
class API {
// ...
public function handleSession() {
$this->auth->handleSession();
}
public function makeRequest() {
$this->auth->makeRequest($this->id, $this->attr);
}
// ...
}
And it would be instantiated as such:
$api = new API;
$api->handleSession();
However this defeats the purpose of having an Auth class in the first place. So I ask you, how can I implement it as I could call handleSession as $api->auth->handleSession();
?