Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Digitalocean V2 Laravel Package

toin0u/digitalocean-v2

Modern DigitalOcean API v2 client for PHP 8.1–8.5. PSR-7/17/18 and HTTPlug compatible, decoupled from any HTTP client. Install via Composer (e.g., with Guzzle) with optional Laravel integration.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require toin0u/digitalocean-v2 guzzlehttp/guzzle
    

    For Laravel, use the framework-specific package:

    composer require graham-campbell/digitalocean
    
  2. Authentication:

    use DigitalOceanV2\Client;
    
    $client = new Client();
    $client->authenticate(env('DIGITALOCEAN_TOKEN')); // Store token in .env
    
  3. First Use Case: Fetch all droplets to verify connectivity:

    $droplets = $client->droplet()->getAll();
    

Key Entry Points

  • Service Accessors: $client->droplet(), $client->database(), etc.
  • Pagination: Built-in ResultPager for collections (e.g., $client->droplet()->getAll() returns paginated results).

Implementation Patterns

Core Workflows

Resource Management

  1. Create/Read/Update/Delete (CRUD):

    // Create a droplet
    $droplet = $client->droplet()->create([
        'name' => 'my-droplet',
        'region' => 'nyc3',
        'size' => 's-1vcpu-1gb',
        'image' => 'ubuntu-22-04-x64'
    ]);
    
    // Update droplet
    $client->droplet()->resize($droplet->id, 's-2vcpu-2gb');
    
    // Delete droplet
    $client->droplet()->remove($droplet->id);
    
  2. Tagging Resources:

    $client->droplet()->addTags($droplet->id, ['env:production', 'team:backend']);
    $client->droplet()->removeTags($droplet->id, ['env:staging']);
    

Database Clusters

  1. Managed Databases:

    // Create a PostgreSQL cluster
    $cluster = $client->database()->createCluster(
        'my-postgres-cluster',
        'pg',
        'db-s-1vcpu-1gb',
        'nyc3',
        1
    );
    
    // Create a database user
    $user = $client->database()->createUser(
        $cluster->id,
        'app_user',
        'mysql_native_password'
    );
    
  2. Replicas and Backups:

    // Create a replica
    $replica = $client->database()->createReplica(
        $cluster->id,
        'replica-db',
        'db-s-1vcpu-1gb'
    );
    
    // Trigger a backup
    $client->database()->createBackup($cluster->id);
    

App Platform

  1. Deployments:

    // Trigger a deployment
    $deployment = $client->app()->createAppDeployment('app-123');
    
    // Stream logs
    $logs = $client->app()->getAggregateDeploymentLogs('app-123', $deployment->id);
    
  2. Configuration:

    // Update app specs
    $client->app()->update('app-123', [
        'services' => [
            [
                'name' => 'web',
                'instance_count' => 3,
            ]
        ]
    ]);
    

CDN Endpoints

  1. Endpoint Management:
    $endpoint = $client->cdnEndpoint()->create([
        'origin' => 'my-bucket.nyc3.digitaloceanspaces.com',
        'ttl' => 3600,
        'certificate_id' => 'cert-123'
    ]);
    

Laravel-Specific Patterns

  1. Service Provider Binding:

    // In AppServiceProvider
    $this->app->singleton(DigitalOceanV2\Client::class, function ($app) {
        $client = new DigitalOceanV2\Client();
        $client->authenticate(config('services.digitalocean.token'));
        return $client;
    });
    
  2. Artisan Commands:

    use Illuminate\Console\Command;
    use DigitalOceanV2\Client;
    
    class DropletListCommand extends Command
    {
        protected $client;
    
        public function __construct(Client $client)
        {
            parent::__construct();
            $this->client = $client;
        }
    
        public function handle()
        {
            $droplets = $this->client->droplet()->getAll();
            $this->table(['ID', 'Name', 'Region'], $droplets);
        }
    }
    
  3. Jobs/Queues:

    use DigitalOceanV2\Client;
    use Illuminate\Bus\Queueable;
    use Illuminate\Contracts\Queue\ShouldQueue;
    
    class CreateDropletJob implements ShouldQueue
    {
        use Queueable;
    
        public function handle(Client $client)
        {
            $client->droplet()->create([
                'name' => 'scheduled-droplet',
                'region' => 'sfo3',
                'size' => 's-1vcpu-1gb',
            ]);
        }
    }
    

Error Handling

  1. HTTP Errors:

    try {
        $client->droplet()->remove('invalid-id');
    } catch (DigitalOceanV2\Exception\ApiErrorException $e) {
        Log::error('Droplet deletion failed: ' . $e->getMessage());
    }
    
  2. Rate Limiting:

    try {
        $client->account()->getUserInformation();
    } catch (DigitalOceanV2\Exception\RateLimitException $e) {
        sleep($e->getRetryAfter());
        retry();
    }
    

Gotchas and Tips

Pitfalls

  1. Authentication:

    • Token Leaks: Never hardcode tokens in source files. Use Laravel’s .env or a secrets manager.
    • Scope Issues: Ensure your token has the correct permissions (e.g., read/write for droplets).
  2. Pagination:

    • Memory Limits: fetchAll() loads all records into memory. Use fetchAllLazy() for large datasets:
      foreach ($client->droplet()->getAllLazy() as $droplet) {
          // Process one by one
      }
      
  3. Idempotency:

    • Droplet Creation: Use idempotency_key to avoid duplicate charges:
      $client->droplet()->create([
          'name' => 'unique-droplet',
          'region' => 'nyc3',
          'idempotency_key' => 'abc123'
      ]);
      
  4. Region-Specific Features:

    • Database Clusters: Not all regions support all database types (e.g., Redis may not be available in nyc3).
  5. Deprecations:

    • Legacy Methods: Some methods (e.g., getAllDroplets()) are deprecated. Use $client->droplet()->getAll() instead.

Debugging Tips

  1. Enable Debugging:

    $client = new Client();
    $client->setDebug(true); // Logs HTTP requests/responses
    
  2. Inspect Raw Responses:

    $response = $client->droplet()->getById('123');
    $rawBody = $response->getRawBody(); // Raw JSON response
    
  3. Common Issues:

    • 404 Errors: Verify resource IDs (e.g., droplet IDs are numeric, clusters are UUIDs).
    • 403 Errors: Check token permissions or rate limits.
    • 500 Errors: Contact DigitalOcean support; may be a temporary API issue.

Extension Points

  1. Custom HTTP Clients: Override the default Guzzle client for retries or middleware:

    use DigitalOceanV2\Http\Client\ClientInterface;
    use DigitalOceanV2\Http\Client\GuzzleClient;
    
    $httpClient = new GuzzleClient([
        'timeout' => 30,
        'headers' => ['User-Agent' => 'MyApp/1.0']
    ]);
    $client = new DigitalOceanV2\Client($httpClient);
    
  2. Event Listeners: Use Laravel’s events to react to API changes:

    // Example: Log droplet creation
    $client->droplet()->create([...])->then(function ($droplet) {
        Log::info("Droplet created: {$droplet->id}");
    });
    
  3. Mocking for Tests:

    use DigitalOceanV2\Client;
    use DigitalOceanV2\Exception\ApiErrorException;
    
    $mockClient = Mockery::mock(Client::class);
    $mockClient->shouldReceive('droplet')
        ->andReturnSelf()
        ->shouldReceive('getAll')
        ->andThrow(new ApiErrorException('Mock error', 404));
    

Performance Tips

  1. Batch Operations: Use bulk endpoints where available (
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky