Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

lucasjose501's avatar

Abstract class for API calls to different services

Hello developers! I'm making an app with the function of grouping and abstracting the interface for displaying and monitoring virtual machines that can be located in different places like Digital Ocean, AWS and OVH, some cases directly on the hypervisor like VMware and Proxmox.

At the moment I don't know exactly the correct term of this pattern about the API side to study on the subject, maybe it's even been addressed here on the forum but I can't find it, so I'll try to explain it briefly:

Each user can have multiple providers, each provider can have multiple VMs, and in the user's dashboard, I want to display all VMs from all their servers in an organized way with some information, for example, if they are powered on or not. The relationship on the database side was not a problem and it works well, but the part of communicating with the APIs that I'm confused because I believe the best way is to create a class that will abstract this information and then have other classes responsible for each provider type.

What would be the best pattern to not make a mess and make it easier to add other providers in the future? For example, it would be like having a single function named "getPowerState" that will be interpreted differently based on the provider type but I'm not sure how to structure the classes and interfaces to manage this. Some connections will be through Rest, others through SSH, so the way to authenticate to each provider is quite different.

Thanks for now and sorry for the wall of texts!

0 likes
1 reply
lucasjose501's avatar
lucasjose501
OP
Best Answer
Level 3

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.

Please or to participate in this conversation.