PHP code example of pstoute / laravel-hosting-management

1. Go to this page and download the library: Download pstoute/laravel-hosting-management library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

pstoute / laravel-hosting-management example snippets


use Pstoute\LaravelHosting\Facades\Hosting;

// Use the default provider
$servers = Hosting::listServers();

// Use a specific provider
$servers = Hosting::driver('forge')->listServers();
$sites = Hosting::driver('gridpane')->listSites();

use Pstoute\LaravelHosting\Facades\Hosting;
use Pstoute\LaravelHosting\Enums\ServerStatus;

// List all servers
$servers = Hosting::listServers();

// Filter operational servers
$operational = $servers->filter(fn ($s) => $s->status === ServerStatus::Active);

// Get a specific server
$server = Hosting::getServer('server-id');

// Create a new server
$server = Hosting::createServer([
    'name' => 'my-new-server',
    'provider' => 'digitalocean',
    'region' => 'nyc1',
    'size' => 's-1vcpu-1gb',
    'php_version' => '8.3',
]);

// Reboot a server
Hosting::rebootServer('server-id');

// Delete a server
Hosting::deleteServer('server-id');

// Get server metrics
$metrics = Hosting::getServerMetrics('server-id');
echo "CPU: {$metrics->cpuUsage}%";
echo "Memory: {$metrics->memoryUsage}%";
echo "Disk: {$metrics->diskUsage}%";

use Pstoute\LaravelHosting\Facades\Hosting;
use Pstoute\LaravelHosting\Enums\PhpVersion;

// List all sites
$sites = Hosting::listSites();

// List sites for a specific server
$sites = Hosting::listSites('server-id');

// Get a specific site
$site = Hosting::getSite('site-id');

// Create a new site
$site = Hosting::createSite('server-id', [
    'domain' => 'example.com',
    'php_version' => '8.3',
    'wordpress' => true,
]);

// Update PHP version
Hosting::setPhpVersion('site-id', PhpVersion::PHP_84);

// Suspend/unsuspend a site
Hosting::suspendSite('site-id');
Hosting::unsuspendSite('site-id');

// Delete a site
Hosting::deleteSite('site-id');

use Pstoute\LaravelHosting\Facades\Hosting;

// Get SSL certificate status
$ssl = Hosting::getSslCertificate('site-id');

if ($ssl && $ssl->expiresSoon(30)) {
    echo "SSL expires in less than 30 days!";
}

// Install Let's Encrypt SSL
$ssl = Hosting::installSslCertificate('site-id');

// Install custom SSL certificate
$ssl = Hosting::installCustomSsl(
    'site-id',
    $certificateContent,
    $privateKeyContent
);

// Remove SSL certificate
Hosting::removeSslCertificate('site-id');

use Pstoute\LaravelHosting\Facades\Hosting;

// List databases on a server
$databases = Hosting::listDatabases('server-id');

// Create a database
$database = Hosting::createDatabase('server-id', 'my_database');

// Create a database user
$user = Hosting::createDatabaseUser('server-id', 'db_user', 'secure_password');

// Delete database
Hosting::deleteDatabase('server-id', 'database-id');

use Pstoute\LaravelHosting\Facades\Hosting;

// Trigger a deployment
$deployment = Hosting::deploy('site-id');

// Check deployment status
$deployment = Hosting::getDeploymentStatus('site-id', $deployment->id);

if ($deployment->isSuccessful()) {
    echo "Deployment completed in {$deployment->humanReadableDuration()}";
}

// List deployment history
$deployments = Hosting::listDeployments('site-id');

// Rollback to a previous deployment
$rollback = Hosting::rollback('site-id', 'deployment-id');

use Pstoute\LaravelHosting\Facades\Hosting;

// List backups
$backups = Hosting::listBackups('site-id');

// Create a backup
$backup = Hosting::createBackup('site-id', [
    'type' => 'full', // or 'database', 'files'
]);

// Restore from backup
Hosting::restoreBackup('site-id', 'backup-id');

// Delete a backup
Hosting::deleteBackup('site-id', 'backup-id');

use Pstoute\LaravelHosting\Facades\Hosting;

// Test connection to the provider
$result = Hosting::testConnection();

if ($result->success) {
    echo "Connected successfully!";
    echo "Latency: {$result->latencyMs}ms";
} else {
    echo "Connection failed: {$result->message}";
}

use Pstoute\LaravelHosting\Facades\Hosting;
use Pstoute\LaravelHosting\Enums\Capability;

// Check if provider supports a capability
if (Hosting::supportsCapability(Capability::GitDeployment)) {
    Hosting::deploy('site-id');
}

// Get all capabilities
$capabilities = Hosting::getCapabilities();

$server->id;            // string
$server->name;          // string
$server->ipAddress;     // ?string
$server->status;        // ServerStatus enum
$server->phpVersion;    // ?PhpVersion enum
$server->isOperational(); // bool
$server->toArray();     // array

$site->id;              // string
$site->serverId;        // string
$site->domain;          // string
$site->status;          // SiteStatus enum
$site->sslEnabled;      // bool
$site->isWordPress;     // bool
$site->hasValidSsl();   // bool

$ssl->status;           // SslStatus enum
$ssl->expiresAt;        // ?DateTimeImmutable
$ssl->isValid();        // bool
$ssl->isExpired();      // bool
$ssl->expiresSoon(30);  // bool (days threshold)

$deployment->status;              // DeploymentStatus enum
$deployment->isSuccessful();      // bool
$deployment->isComplete();        // bool
$deployment->durationSeconds;     // ?int
$deployment->humanReadableDuration(); // string

$metrics->cpuUsage;              // float
$metrics->memoryUsage;           // float
$metrics->diskUsage;             // float
$metrics->isCpuCritical(90);     // bool
$metrics->isMemoryCritical(90);  // bool
$metrics->humanReadableUptime(); // string

ServerStatus::Provisioning
ServerStatus::Active
ServerStatus::Inactive
ServerStatus::Rebooting
ServerStatus::Failed
ServerStatus::Deleting
ServerStatus::Unknown

SiteStatus::Installing
SiteStatus::Active
SiteStatus::Suspended
SiteStatus::Maintenance
SiteStatus::Failed
SiteStatus::Deleting
SiteStatus::Unknown

PhpVersion::PHP_74
PhpVersion::PHP_80
PhpVersion::PHP_81
PhpVersion::PHP_82
PhpVersion::PHP_83
PhpVersion::PHP_84

// Utilities
PhpVersion::fromString('8.3');     // PhpVersion::PHP_83
PhpVersion::latest();               // PhpVersion::PHP_84
PhpVersion::recommended();          // PhpVersion::PHP_83
PhpVersion::PHP_83->isSupported(); // bool

Capability::ServerManagement
Capability::SiteManagement
Capability::DatabaseManagement
Capability::SslInstallation
Capability::GitDeployment
Capability::AutoDeployment
Capability::Backups
// ... and more

// Server events
Pstoute\LaravelHosting\Events\ServerCreated
Pstoute\LaravelHosting\Events\ServerProvisioned
Pstoute\LaravelHosting\Events\ServerDeleted
Pstoute\LaravelHosting\Events\ServerRebooted

// Site events
Pstoute\LaravelHosting\Events\SiteCreated
Pstoute\LaravelHosting\Events\SiteDeleted
Pstoute\LaravelHosting\Events\SiteSuspended
Pstoute\LaravelHosting\Events\SiteUnsuspended

// SSL events
Pstoute\LaravelHosting\Events\SslCertificateInstalled
Pstoute\LaravelHosting\Events\SslCertificateExpiring

// Deployment events
Pstoute\LaravelHosting\Events\DeploymentStarted
Pstoute\LaravelHosting\Events\DeploymentCompleted
Pstoute\LaravelHosting\Events\DeploymentFailed

// Backup events
Pstoute\LaravelHosting\Events\BackupCreated
Pstoute\LaravelHosting\Events\BackupRestored

protected $listen = [
    \Pstoute\LaravelHosting\Events\DeploymentCompleted::class => [
        \App\Listeners\NotifyDeploymentComplete::class,
    ],
];

use Pstoute\LaravelHosting\Exceptions\HostingException;
use Pstoute\LaravelHosting\Exceptions\ServerNotFoundException;
use Pstoute\LaravelHosting\Exceptions\SiteNotFoundException;
use Pstoute\LaravelHosting\Exceptions\AuthenticationException;
use Pstoute\LaravelHosting\Exceptions\RateLimitException;
use Pstoute\LaravelHosting\Exceptions\ProvisioningException;

try {
    $server = Hosting::getServer('invalid-id');
} catch (ServerNotFoundException $e) {
    // Server not found
} catch (AuthenticationException $e) {
    // Invalid API credentials
} catch (RateLimitException $e) {
    // Too many requests, retry after: $e->retryAfter
} catch (HostingException $e) {
    // Generic hosting error
}

use Pstoute\LaravelHosting\Testing\FakeHostingProvider;
use Pstoute\LaravelHosting\Facades\Hosting;
use Pstoute\LaravelHosting\Data\Server;

public function test_it_creates_a_server(): void
{
    $fake = new FakeHostingProvider();

    // Swap the provider
    Hosting::swap($fake);

    // Pre-seed data
    $fake->withServers([
        Server::fromArray([
            'id' => '1',
            'name' => 'existing-server',
            'status' => 'active',
        ]),
    ]);

    // Your test code
    $servers = Hosting::listServers();
    $this->assertCount(1, $servers);

    // Create a server
    $server = Hosting::createServer(['name' => 'new-server']);

    // Assertions
    $fake->assertServerCreated('new-server');
    $fake->assertMethodCalled('createServer');
    $fake->assertMethodNotCalled('deleteServer');
}

public function test_it_handles_failures(): void
{
    $fake = new FakeHostingProvider();
    $fake->shouldFailWith('Simulated API error');

    Hosting::swap($fake);

    $this->expectException(\Pstoute\LaravelHosting\Exceptions\HostingException::class);

    Hosting::listServers();
}

$fake->assertServerCreated(?string $name = null);
$fake->assertSiteCreated(?string $domain = null);
$fake->assertSslInstalled(?string $siteId = null);
$fake->assertDeployed(?string $siteId = null);
$fake->assertBackupCreated(?string $siteId = null);
$fake->assertMethodCalled(string $method, ?int $times = null);
$fake->assertMethodNotCalled(string $method);
$fake->getRecordedCalls(); // Get all recorded method calls
$fake->getCallsTo(string $method); // Get calls to specific method

$fake->withServers([...]); // Pre-populate servers
$fake->withSites([...]);   // Pre-populate sites
$fake->withDatabases([...]);
$fake->withCapabilities([Capability::ServerManagement]);
$fake->shouldFailWith('Error message');
$fake->notConfigured();
$fake->reset(); // Reset all state

// config/hosting.php
'cache' => [
    'enabled' => env('HOSTING_CACHE_ENABLED', true),
    'prefix' => 'hosting:',
    'ttl' => [
        'servers' => 300,       // 5 minutes
        'sites' => 300,         // 5 minutes
        'ssl' => 3600,          // 1 hour
        'databases' => 600,     // 10 minutes
        'deployments' => 0,     // Never cache
    ],
],

// config/hosting.php
'rate_limits' => [
    'enabled' => env('HOSTING_RATE_LIMIT_ENABLED', true),
    'per_minute' => env('HOSTING_RATE_LIMIT_PER_MINUTE', 60),
],

use Pstoute\LaravelHosting\Facades\Hosting;

public function boot(): void
{
    Hosting::extend('custom', function ($app, $config) {
        return new CustomHostingProvider($config);
    });
}
bash
php artisan vendor:publish --provider="Pstoute\LaravelHosting\HostingServiceProvider"