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

Client Laravel Package

platformsh/client

PHP client library for the Platform.sh API. Authenticate with an API token, then manage projects, environments, and activities (e.g., branch operations) and create subscriptions. Used by the Platform.sh CLI; supports PHP 8.2+ in v3.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require platformsh/client
    

    Ensure your project uses PHP 8.2+ (for 3.x branch).

  2. First Configuration:

    use Platformsh\Client\Connection\Connector;
    use Platformsh\Client\PlatformClient;
    
    $connector = new Connector([
        'api_url' => 'https://api.platform.sh',
        'accounts' => 'https://api.platform.sh/',
        'centralized_permissions_enabled' => true,
    ]);
    
    $client = new PlatformClient($connector);
    $client->getConnector()->setApiToken('YOUR_API_TOKEN', 'exchange');
    
  3. First Use Case: Fetch a project and its default environment:

    $project = $client->getProject('project_id');
    $environment = $project->getEnvironment($project->default_branch);
    

Key Entry Points

  • PlatformClient: Main entry point for all API interactions.
  • Connector: Handles authentication and API endpoint configuration.
  • Project/Environment Methods: Direct access to project/environment operations (e.g., runOperation(), getVariables()).

Implementation Patterns

Workflows

  1. Project Management:

    // List projects
    $projects = $client->getProjects();
    
    // Create a project (via CLI or API)
    $project = $client->createProject(['name' => 'my-project']);
    
    // Update project settings
    $project->update(['description' => 'Updated via API']);
    
  2. Environment Operations:

    // Trigger a build
    $environment->runOperation('build');
    
    // Deploy code
    $environment->runOperation('deploy', [
        'source' => 'git://github.com/user/repo.git',
    ]);
    
    // Get environment variables
    $variables = $environment->getVariables();
    
  3. Service Management:

    // List services in an environment
    $services = $environment->getServices();
    
    // Scale a service
    $service->scale(['count' => 3]);
    

Integration Tips

  • Laravel Service Provider: Bind the client to the container for dependency injection:

    $this->app->singleton(PlatformClient::class, function ($app) {
        $connector = new Connector(config('platformsh'));
        $client = new PlatformClient($connector);
        $client->getConnector()->setApiToken(config('platformsh.token'), 'exchange');
        return $client;
    });
    
  • Command Bus: Use Laravel’s Bus facade to dispatch API calls as jobs:

    Bus::dispatch(new DeployEnvironment($environmentId, $branch));
    
  • Event Listeners: Listen for Platform.sh webhooks (e.g., environment events) and trigger Laravel events:

    $environment->on('deploy:finished', function () {
        event(new EnvironmentDeployed($environment));
    });
    
  • Configuration: Store API tokens and endpoints in .env:

    PLATFORMSH_API_TOKEN=your_token_here
    PLATFORMSH_API_URL=https://api.platform.sh
    

Gotchas and Tips

Pitfalls

  1. Token Management:

    • Never hardcode tokens. Use environment variables or Laravel’s config.
    • Tokens are project-specific (e.g., exchange, project_id). Ensure you set the correct scope:
      $client->getConnector()->setApiToken($token, 'exchange'); // For org-wide access
      $client->getConnector()->setApiToken($token, 'project_id'); // For project-specific access
      
  2. Rate Limiting:

    • Platform.sh API enforces rate limits (~60 requests/minute). Cache responses aggressively:
      $project = Cache::remember("platformsh.project.{$projectId}", now()->addMinutes(5), fn() =>
          $client->getProject($projectId)
      );
      
  3. Environment States:

    • Operations like deploy or build may fail silently if the environment is in an invalid state (e.g., error). Always check:
      if ($environment->state !== 'running') {
          throw new \RuntimeException("Environment not ready for operations.");
      }
      
  4. Branch vs. Environment:

    • getEnvironment($branch) assumes the branch exists. Use getEnvironmentById($id) for reliability:
      $environment = $project->getEnvironmentById($environmentId);
      
  5. Centralized Permissions:

    • If centralized_permissions_enabled is true, ensure your token has the correct org-level permissions. Test with:
      $client->getConnector()->setCentralizedPermissionsEnabled(true);
      

Debugging

  • Enable Debug Mode:
    $connector->setDebug(true); // Logs raw API requests/responses
    
  • Handle Exceptions: Wrap API calls in try-catch blocks:
    try {
        $environment->runOperation('deploy');
    } catch (\Platformsh\Client\Exception\ApiException $e) {
        \Log::error("Platform.sh API error: " . $e->getMessage());
    }
    

Extension Points

  1. Custom Operations: Extend the client to add project-specific operations:

    class CustomPlatformClient extends PlatformClient {
        public function customOperation($projectId, $data) {
            $project = $this->getProject($projectId);
            return $project->runOperation('custom', $data);
        }
    }
    
  2. Webhook Validation: Validate incoming Platform.sh webhooks using the client’s verifyWebhook method:

    $isValid = $client->verifyWebhook(
        $request->input('signature'),
        $request->getContent(),
        $webhookSecret
    );
    
  3. Mocking for Tests: Use Laravel’s Mockery to stub the client:

    $mockClient = Mockery::mock(PlatformClient::class);
    $mockClient->shouldReceive('getProject')
               ->once()
               ->andReturn($mockProject);
    
  4. Async Operations: Poll for operation status using waitForOperation:

    $operation = $environment->runOperation('deploy');
    $result = $operation->waitForOperation(); // Blocks until completion
    
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.
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
spatie/mailcoach-vapor