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

Phpsdk Laravel Package

christhompsontldr/phpsdk

PHP SDK for the Cloudways API. Install via Composer, authenticate with your email and API key, and manage Cloudways resources like servers, regions, providers, sizes, and apps. Includes helpers to check and wait for async operation status/results.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require cloudwaysapi/phpsdk:1.0.0.x-dev
    

    Or add to composer.json:

    {
        "require": {
            "cloudwaysapi/phpsdk": "1.0.0.x-dev"
        }
    }
    
  2. Environment Configuration (Laravel): Add credentials to .env:

    CW_EMAIL=your@cloudways.com
    CW_API_KEY=your_api_key_here
    
  3. First Use Case: Fetch server regions in a Laravel controller:

    use Cloudways\Lists\Lists;
    
    class ServerController extends Controller {
        public function regions() {
            $list = new Lists();
            $list->setEmail(env('CW_EMAIL'));
            $list->setKey(env('CW_API_KEY'));
            return $list->getServerRegions();
        }
    }
    

Implementation Patterns

Core Workflows

  1. Resource Management:

    • Server Operations:
      $server = new \Cloudways\Server\Server();
      $server->setEmail(env('CW_EMAIL'));
      $server->setKey(env('CW_API_KEY'));
      
      // Create server
      $params = ['cloud' => 'do', 'region' => 'lon1', 'application' => 'phpstack'];
      $result = $server->create_server($params);
      
      // Poll operation status
      $operationId = $result['operation_id'];
      $isComplete = $server->getOperation($operationId)['completed'];
      
  2. List Operations (Laravel Service Layer):

    class CloudwaysService {
        protected $lists;
    
        public function __construct() {
            $this->lists = new Lists();
            $this->lists->setEmail(env('CW_EMAIL'));
            $this->lists->setKey(env('CW_API_KEY'));
        }
    
        public function getAllLists() {
            return [
                'regions' => $this->lists->getServerRegions(),
                'clouds' => $this->lists->getCloudProviders(),
                // ... other lists
            ];
        }
    }
    
  3. Asynchronous Polling (Job Queue):

    // In a Laravel job
    public function handle() {
        $operationId = $this->data['operation_id'];
        $server = new \Cloudways\Server\Server();
        $server->setEmail(env('CW_EMAIL'));
        $server->setKey(env('CW_API_KEY'));
    
        if (!$server->getOperationResult($operationId, 5)) {
            $this->release(60); // Retry after 60 seconds
        }
    }
    

Integration Tips

  • Dependency Injection: Bind the SDK to Laravel’s container in AppServiceProvider:

    $this->app->bind(\Cloudways\Lists\Lists::class, function ($app) {
        $lists = new Lists();
        $lists->setEmail(env('CW_EMAIL'));
        $lists->setKey(env('CW_API_KEY'));
        return $lists;
    });
    
  • API Rate Limiting: Implement a decorator to handle rate limits:

    class RateLimitedCloudwaysService {
        public function getWithRetry($method, $params, $retries = 3) {
            try {
                return $this->cloudways->$method($params);
            } catch (\GuzzleHttp\Exception\RequestException $e) {
                if ($retries && $this->isRateLimitError($e)) {
                    sleep(2);
                    return $this->getWithRetry($method, $params, $retries - 1);
                }
                throw $e;
            }
        }
    }
    

Gotchas and Tips

Common Pitfalls

  1. Operation Polling:

    • getOperationResult() may hit PHP’s max_execution_time. Use Laravel queues/jobs for long-running operations.
    • Example queue job:
      class PollOperationJob implements ShouldQueue {
          public function handle() {
              $server = new \Cloudways\Server\Server();
              $server->setEmail(env('CW_EMAIL'));
              $server->setKey(env('CW_API_KEY'));
      
              if (!$server->getOperationResult($this->operationId, 10)) {
                  $this->release(30); // Retry after 30 seconds
              }
          }
      }
      
  2. Authentication:

    • Hardcoding credentials in code violates security. Always use .env and validate them in AppServiceProvider:
      if (empty(env('CW_API_KEY'))) {
          throw new \RuntimeException('Cloudways API key not configured.');
      }
      
  3. Deprecated Methods:

    • The SDK uses SetEmail/SetKey (PascalCase). Prefer Laravel’s dependency injection or a wrapper:
      class CloudwaysWrapper {
          public function __construct() {
              $this->server = new \Cloudways\Server\Server();
              $this->server->setEmail(env('CW_EMAIL'));
              $this->server->setKey(env('CW_API_KEY'));
          }
      }
      

Debugging Tips

  1. Enable Guzzle Debugging: Add to AppServiceProvider:

    \GuzzleHttp\HandlerStack::setDefaultHandler(
        \GuzzleHttp\HandlerStack::create(new \GuzzleHttp\Middleware::tap(function ($request) {
            \Log::debug('Cloudways API Request:', [
                'url' => (string) $request->getUri(),
                'method' => $request->getMethod(),
                'body' => $request->getBody() ? $request->getBody()->getContents() : null,
            ]);
        }))
    );
    
  2. Operation ID Logging: Log operation IDs for manual API inspection:

    \Log::info('Cloudways Operation Started', ['operation_id' => $result['operation_id']]);
    

Extension Points

  1. Custom Endpoints: Extend the SDK for private API endpoints:

    class ExtendedCloudwaysService extends \Cloudways\Lists\Lists {
        public function customEndpoint($endpoint, $params) {
            return $this->makeRequest('GET', "/api/v1/$endpoint", $params);
        }
    }
    
  2. Webhook Integration: Validate Cloudways webhook signatures:

    public function verifyWebhook($payload, $signature) {
        $expected = hash_hmac('sha256', $payload, env('CW_API_KEY'));
        return hash_equals($expected, $signature);
    }
    
  3. Caching: Cache list operations (e.g., regions, clouds) with Laravel’s cache:

    public function getServerRegions() {
        return cache()->remember('cloudways.regions', now()->addHours(1), function () {
            return parent::getServerRegions();
        });
    }
    
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.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
milesj/emojibase
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport