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

Digital Ocean Bundle Laravel Package

dunglas/digital-ocean-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Install the Bundle:

    composer require dunglas/digital-ocean-bundle symfony/http-client nyholm/psr7 guzzlehttp/promises
    

    Add to config/bundles.php:

    Dunglas\DigitalOceanBundle\DunglasDigitalOceanBundle::class => ['all' => true],
    
  2. Configure API Token: In .env:

    DIGITAL_OCEAN_TOKEN=your_digital_ocean_api_token
    

    Or in config/packages/dunglas_digital_ocean.yaml:

    dunglas_digital_ocean: "%env(DIGITAL_OCEAN_TOKEN)%"
    
  3. First Use Case: Inject the Client into a controller or command:

    use DigitalOceanV2\Client;
    
    #[Route('/droplets', name: 'list_droplets')]
    public function listDroplets(Client $doClient): Response
    {
        $droplets = $doClient->droplet()->getAll();
        return $this->json($droplets);
    }
    

Where to Look First


Implementation Patterns

Usage Patterns

  1. Dependency Injection:

    • Inject DigitalOceanV2\Client into any Symfony service (controllers, commands, event subscribers, etc.).
    • Use named clients for multi-environment setups:
      # config/packages/dunglas_digital_ocean.yaml
      dunglas_digital_ocean:
        connections:
          production: "%env(DIGITAL_OCEAN_PROD_TOKEN)%"
          staging: "%env(DIGITAL_OCEAN_STAGING_TOKEN)%"
        default_connection: production
      
      Then inject:
      public function __construct(
          private Client $productionClient,
          private Client $stagingClient
      ) {}
      
  2. Pagination Handling:

    • Use ResultPager for large datasets:
      $pager = new ResultPager($doClient);
      $droplets = $pager->fetchAll($doClient->droplet(), 'getAll');
      
    • Implement custom pagination logic for APIs:
      use Symfony\Component\Serializer\Normalizer\AbstractNormalizer;
      
      #[ApiResource(
          normalizationContext: ['groups' => ['droplet:read']],
          paginationItemsPerPage: 20
      )]
      class Droplet {}
      
  3. Async Operations:

    • Offload long-running tasks to Symfony Messenger:
      use Symfony\Component\Messenger\Attribute\AsMessageHandler;
      
      #[AsMessageHandler]
      public function handle(CreateDropletMessage $message, Client $doClient)
      {
          $doClient->droplet()->create($message->dropletData);
      }
      
  4. API Platform Integration:

    • Expose DigitalOcean resources as API endpoints:
      #[ApiResource(
          operations: [
              new GetCollection(),
              new Get(),
              new Post(
                  uriTemplate: '/droplets',
                  validationContext: ['groups' => ['droplet:create']]
              )
          ]
      )]
      class Droplet {}
      
    • Use ApiPlatform\Metadata\Operation to customize API methods:
      #[ApiResource]
      class Droplet
      {
          #[Get(name: 'get_droplet_actions')]
          public function getActions(Client $doClient, string $id): array
          {
              return $doClient->droplet()->actions()->get($id);
          }
      }
      
  5. Command-Line Automation:

    • Create console commands for DevOps tasks:
      use Symfony\Component\Console\Command\Command;
      use Symfony\Component\Console\Input\InputInterface;
      use Symfony\Component\Console\Output\OutputInterface;
      
      class ScaleDropletsCommand extends Command
      {
          protected static $defaultName = 'do:scale-droplets';
      
          protected function execute(InputInterface $input, OutputInterface $output, Client $doClient): int
          {
              $droplets = $doClient->droplet()->getAll();
              foreach ($droplets as $droplet) {
                  if ($droplet->memory < 2) {
                      $doClient->droplet()->resize($droplet->id, 's-2vcpu-2gb');
                  }
              }
              return Command::SUCCESS;
          }
      }
      

Workflows

  1. Provisioning Workflow:

    • Use a form + API Platform to create droplets dynamically:
      #[Post('/deploy', name: 'deploy_app')]
      public function deploy(
          Request $request,
          Client $doClient,
          EntityManagerInterface $em
      ): Response {
          $data = json_decode($request->getContent(), true);
          $droplet = $doClient->droplet()->create($data['droplet']);
          $em->persist($droplet); // Store in your DB
          return $this->json(['droplet_id' => $droplet->id]);
      }
      
  2. Monitoring Workflow:

    • Poll droplet statuses and trigger alerts:
      use Symfony\Component\Console\Command\Command;
      use Symfony\Component\Console\Input\InputInterface;
      use Symfony\Component\Console\Output\OutputInterface;
      
      class MonitorDropletsCommand extends Command
      {
          protected static $defaultName = 'do:monitor-droplets';
      
          protected function execute(InputInterface $input, OutputInterface $output, Client $doClient): int
          {
              $droplets = $doClient->droplet()->getAll();
              foreach ($droplets as $droplet) {
                  if ($droplet->status === 'new') {
                      $output->writeln("Droplet {$droplet->id} is still provisioning!");
                  }
              }
              return Command::SUCCESS;
          }
      }
      
  3. Cleanup Workflow:

    • Automate resource cleanup (e.g., delete unused droplets):
      use Symfony\Component\Console\Command\Command;
      use Symfony\Component\Console\Input\InputInterface;
      use Symfony\Component\Console\Output\OutputInterface;
      
      class CleanupDropletsCommand extends Command
      {
          protected static $defaultName = 'do:cleanup-droplets';
      
          protected function execute(InputInterface $input, OutputInterface $output, Client $doClient): int
          {
              $droplets = $doClient->droplet()->getAll();
              foreach ($droplets as $droplet) {
                  if ($droplet->createdAt < new \DateTime('-30 days')) {
                      $doClient->droplet()->delete($droplet->id);
                      $output->writeln("Deleted droplet {$droplet->id}");
                  }
              }
              return Command::SUCCESS;
          }
      }
      

Integration Tips

  1. Testing:

    • Mock the Client in tests using Mockery or PHPUnit:
      use DigitalOceanV2\Client;
      use DigitalOceanV2\Droplet\Droplet;
      
      $mockClient = Mockery::mock(Client::class);
      $mockClient->shouldReceive('droplet')->andReturnSelf();
      $mockClient->shouldReceive('getAll')->andReturn([new Droplet(['id' => 1])]);
      
      $this->container->set(Client::class, $mockClient);
      
  2. Error Handling:

    • Wrap API calls in try-catch blocks and log errors:
      try {
          $droplet = $doClient->droplet()->get($id);
      } catch (\DigitalOceanV2\Exception\ApiException $e) {
          $this->logger->error('Failed to fetch droplet: ' . $e->getMessage());
          throw new \RuntimeException('Droplet not found', 404, $e);
      }
      
  3. Caching:

    • Cache API responses to reduce rate limit usage:
      use Symfony\Contracts\Cache\CacheInterface;
      
      public function __construct(
          private Client $doClient,
          private CacheInterface $cache
      ) {}
      
      public function getDroplets(): array
      {
          return $this->cache->get('droplets', function () {
              return $this->doClient->droplet()->getAll();
          }, 300); // Cache for 5 minutes
      }
      
  4. Webhooks:

    • Use Symfony Messenger to handle DigitalOcean webhook events:
      use Symfony\Component\Messenger\Attribute\AsMessageHandler;
      
      #[AsMessageHandler]
      public function handleWebhook(DigitalOceanWebhookMessage $message, Client $doClient)
      {
          if ($message->event === 'droplet.create') {
              $droplet = $doClient->droplet()->get($message->dropletId);
      
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.
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge