I managed to do something that turned out really good so far.
I have 4 files for this demo:
- Contracts/ServerProviderApi.php
- Services/ServerProvider.php
- Services/ServerProvider/Vcenter.php
- Services/ServerProvider/Ovh.php
The ServerProvider have a static boot function that accepts an server model and return a new Instance of Vcenter or Ovh, both implements the interface ServerProviderApi.
public static function boot(Server $server): ServerProviderApi
{
return match ($server->type) {
ServerType::vCenter => new Vcenter($server),
ServerType::OVH => new Ovh($server),
default => throw new Exception('Invalid server type.')
};
}
To initialize the API I'm using:
$api = ServerProvider::boot($server);
This way I can use it like:
echo $api->ping(); // 'pong from vCenter'
And I think this is a good solution. In the future if I want to add a new server type I'll just need a new class that implements the interface and add it in the ServerProvider to "discover" the right class.