i'm using an external API that posts products and orders into a marketplace, and it provides a class that in each request i have to specify an endpoint
, user
and password (token)
, it's something like this:
if($env == 'testing') {
$endpoint = 'testing';
$user = 'testing';
$pass = 'testing';
} else {
$endpoint = 'production';
$user = 'production';
$pass = 'production';
}
$itemSender = new ItemSender($endpoint, $user, $pass);
$orderSender = new OrderSender($endpoint, $user, $pass);
my first thought was to use the strategy pattern so i can have both testing and production environment, or even others environments, implementing an interface, i built something lie this:
interface EnviromentInterface () {
function getEndpoint();
function getUser();
function getPassword();
}
class TestingEnvironment implements EnviromentInterface {
private $endpoint;
private $user;
private $password;
function getEndpoint() {
return $this->endpoint;
// return getFromConfigFile('API_ENDPOINT_TESTING');
}
function getUser() {
return $this->user;
}
function getPassword() {
return $this->password;
}
}
class ProductionEnviroment implements EnviromentInterface {
private $endpoint;
private $user;
private $password;
function getEndpoint() {
return $this->endpoint;
// return getFromConfigFile('API_ENDPOINT_PRODUCTION');
}
function getUser() {
return $this->user;
}
function getPassword() {
return $this->password;
}
}
and i would overwrite the parent's class construct
to use the environment object, something like this:
class CustomItemSender extends ItemSender
{
function __construct(EnviromentInterface $env)
{
parent::__construct($env->getEndpoint(), $env->getUser(), $env->getPassword());
}
}
the problem is: how can i switch between these environment objects? i thought about using a switch/case
, but if i need to implement more environments i have to add another if to the switch/case statment.
what would be a good aproach in this case?
important: all info/credentials about the testing and production environments are inside a config file, that in this case is an .env
file