Skip to content

Instantly share code, notes, and snippets.

@felipevolpatto
Last active October 22, 2019 18:39
Show Gist options
  • Save felipevolpatto/0f2efc66ea2fa725de22a6596c77f9b4 to your computer and use it in GitHub Desktop.
Save felipevolpatto/0f2efc66ea2fa725de22a6596c77f9b4 to your computer and use it in GitHub Desktop.
Design patterns: Strategy pattern
<?php
namespace Strategy\Auth;
use Strategy\AuthInterface;
use Bling\Controller\UserController;
class ApiKeyStrategy implements AuthInterface {
public function authenticate(...$params): bool {
$userController = new UserController();
return $userController->getByApiKey($params['apikey']);
}
}
<?php
namespace Strategy;
use Strategy\AuthInterface;
class AuthContext {
private static $authStrategy;
public static function setAuthStrategy(AuthInterface $authStrategy): void {
self::$authStrategy = $authStrategy;
}
public static function authenticate(...$params): bool {
return self::$authStrategy->authenticate($params);
}
}
<?php
namespace Strategy;
interface AuthInterface {
public function authenticate(...$params): bool;
}
<?php
use Strategy\Auth\ApiKeyStrategy;
use Strategy\Auth\LoginStrategy;
use Strategy\Auth\OAuth2Strategy;
// Quando a requisição vier da interface
AuthContext::setAuthStrategy(new LoginStrategy());
AuthContext::authenticate([
'login' => '',
'pass' => ''
]);
// Quando a requisição vier da API utilizando API Key
AuthContext::setAuthStrategy(new ApiKeyStrategy());
AuthContext::authenticate([
'apikey' => ''
]);
// Quando a requisição vier da API utilizando OAuth2
AuthContext::setAuthStrategy(new OAuth2Strategy());
AuthContext::authenticate([
'accessToken' => ''
]);
<?php
namespace Strategy\Auth;
use Strategy\AuthInterface;
use Bling\Controller\UserController;
class LoginStrategy implements AuthInterface {
public function authenticate(...$params): bool {
$userController = new UserController();
return $userController->getByLogin($params['login'], $params['pass']);
}
}
<?php
namespace Strategy\Auth;
use Strategy\AuthInterface;
use Bling\Controller\UserController;
class OAuth2Strategy implements AuthInterface {
public function authenticate(...$params): bool {
$userController = new UserController();
return $userController->getByAccessToken($params['accessToken']);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment