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.
Installation:
composer require platformsh/client
Ensure your project uses PHP 8.2+ (for 3.x branch).
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');
First Use Case: Fetch a project and its default environment:
$project = $client->getProject('project_id');
$environment = $project->getEnvironment($project->default_branch);
PlatformClient: Main entry point for all API interactions.Connector: Handles authentication and API endpoint configuration.runOperation(), getVariables()).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']);
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();
Service Management:
// List services in an environment
$services = $environment->getServices();
// Scale a service
$service->scale(['count' => 3]);
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
Token Management:
config.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
Rate Limiting:
$project = Cache::remember("platformsh.project.{$projectId}", now()->addMinutes(5), fn() =>
$client->getProject($projectId)
);
Environment States:
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.");
}
Branch vs. Environment:
getEnvironment($branch) assumes the branch exists. Use getEnvironmentById($id) for reliability:
$environment = $project->getEnvironmentById($environmentId);
Centralized Permissions:
centralized_permissions_enabled is true, ensure your token has the correct org-level permissions. Test with:
$client->getConnector()->setCentralizedPermissionsEnabled(true);
$connector->setDebug(true); // Logs raw API requests/responses
try {
$environment->runOperation('deploy');
} catch (\Platformsh\Client\Exception\ApiException $e) {
\Log::error("Platform.sh API error: " . $e->getMessage());
}
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);
}
}
Webhook Validation:
Validate incoming Platform.sh webhooks using the client’s verifyWebhook method:
$isValid = $client->verifyWebhook(
$request->input('signature'),
$request->getContent(),
$webhookSecret
);
Mocking for Tests:
Use Laravel’s Mockery to stub the client:
$mockClient = Mockery::mock(PlatformClient::class);
$mockClient->shouldReceive('getProject')
->once()
->andReturn($mockProject);
Async Operations:
Poll for operation status using waitForOperation:
$operation = $environment->runOperation('deploy');
$result = $operation->waitForOperation(); // Blocks until completion
How can I help you explore Laravel packages today?