Weave 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

Ecs 20140526 Laravel Package

alibabacloud/ecs-20140526

Official Alibaba Cloud ECS (20140526) SDK for PHP, offering typed APIs to create, manage, and monitor cloud servers, disks, images, snapshots, security groups, and networking resources. Easy Composer integration with broad ECS API coverage.

View on GitHub
Deep Wiki
Context7

Getting Started

This is the official, auto-generated Alibaba Cloud ECS (Elastic Compute Service) SDK for PHP, pinned to API version 20140526. It is not a Laravel package — no service provider, no facade, no config file. You install it, build a client, and call one method per ECS OpenAPI action. Treat it as a typed HTTP client for the ECS API.

Install

composer require alibabacloud/ecs-20140526

It pulls in the Darabonba/OpenAPI runtime (alibabacloud/darabonba-openapi or alibabacloud/openapi-core depending on release) plus tea — those are the packages you actually debug when things go wrong.

Where to look first

  1. vendor/alibabacloud/ecs-20140526/src/Ecs.php — the client. Every API action is a public method here (describeInstances, runInstances, …). This is your real API index; the README is minimal.
  2. vendor/alibabacloud/ecs-20140526/src/Models/ — request/response classes. DescribeInstancesRequest shows exactly which parameters exist and their casing.
  3. The official API reference at help.aliyun.com for ECS — match the action name, then find the camelCase method and model in src/.
  4. Environment variables: ALIBABA_CLOUD_ACCESS_KEY_ID, ALIBABA_CLOUD_ACCESS_KEY_SECRET, ALIBABA_CLOUD_SECURITY_TOKEN (for STS).

First use case — list instances in a region

use AlibabaCloud\SDK\Ecs\V20140526\Ecs;
use AlibabaCloud\SDK\Ecs\V20140526\Models\DescribeInstancesRequest;
use Darabonba\OpenApi\Models\Config;

$config = new Config([
    'accessKeyId'     => env('ALIBABA_CLOUD_ACCESS_KEY_ID'),
    'accessKeySecret' => env('ALIBABA_CLOUD_ACCESS_KEY_SECRET'),
    'endpoint'        => 'ecs.cn-hangzhou.aliyuncs.com', // must match the region you query
]);

$client = new Ecs($config);

$request = new DescribeInstancesRequest([
    'regionId' => 'cn-hangzhou',
    'pageSize' => 20,
    'pageNumber' => 1,
]);

$response = $client->describeInstances($request);

foreach ($response->body->instances->instance ?? [] as $instance) {
    echo $instance->instanceId, ' ', $instance->status, PHP_EOL;
}

If that returns data, the rest of the SDK is the same shape: new request model → call method → walk $response->body.

Implementation Patterns

Wrap the client in a Laravel service / singleton. Nothing in the SDK knows about the container. Bind a configured client once:

// AppServiceProvider::register()
$this->app->singleton(Ecs::class, function () {
    return new Ecs(new Config([
        'accessKeyId'     => config('services.aliyun.key'),
        'accessKeySecret' => config('services.aliyun.secret'),
        'securityToken'   => config('services.aliyun.token'), // optional, STS
        'endpoint'        => config('services.aliyun.ecs_endpoint'),
        'connectTimeout'  => 5000,
        'readTimeout'     => 30000,
    ]));
});

Then inject Ecs into jobs, commands, and services. Do not new Ecs(...) per request — client construction is cheap but credential resolution and HTTP setup are wasted work.

Use ...WithOptions for retries and timeouts per call. The plain methods have no retry. The WithOptions variants take a RuntimeOptions object:

use Darabdoba\OpenApi\Models\RuntimeOptions;

$runtime = new RuntimeOptions([
    'autoretry'      => true,
    'maxAttempts'    => 3,
    'connectTimeout' => 5000,
    'readTimeout'    => 30000,
]);

$response = $client->describeInstancesWithOptions($request, $runtime);

Put this behind a small helper so every call site gets retry behavior — ECS throttles aggressively during bulk operations.

Idempotency with ClientToken. Mutating actions (runInstances, createSnapshot, attachDisk) accept a clientToken. Generate a UUID, store it alongside your job record, and reuse it on retry. This is the only reliable way to avoid duplicate instances when a request times out after the API already accepted it:

$request = new RunInstancesRequest([
    'regionId'    => 'cn-hangzhou',
    'clientToken' => (string) Str::uuid(),
    'imageId'     => 'ubuntu_22_04_x64_20G_alibase_20240101.vhd',
    'instanceType'=> 'ecs.g7.large',
    'amount'      => 1,
]);

Persist the token before dispatch; on a queue retry, reuse it.

Async lifecycle is not async. runInstances, startInstance, stopInstance return immediately with a requestId, not a finished resource. Poll describeInstances / describeInstanceStatus in a queued job with backoff. There are no waiters in the PHP SDK:

$response = $client->runInstances($request);
$ids = $response->body->instanceIdSets->instanceIdSet;
// enqueue PollInstanceStatusJob with $ids

Pagination is not uniform. Three schemes exist in this API:

  • pageNumber/pageSize — describeInstances, describeImages, describeSnapshots
  • nextToken/maxResults — describeSecurityGroups, newer APIs
  • maxResults only, no token — some list endpoints

Check the specific *Request class in src/Models/ rather than assuming. Loop until the returned array is shorter than pageSize (page style) or nextToken is null (token style).

Tags instead of naming conventions for ownership. listTagResources / tagResources / untagResources let you encode tenant, environment, and cost-center on every resource. Do this at creation time via the tags parameter on RunInstancesRequest, not as a follow-up call — follow-up tagging fails silently often enough to matter in billing reports.

Bulk operations go through the queue. describeInstances returns up to 100 per page; a fleet of thousands means many calls. Fan out across queued jobs with Bus::batch(), throttle concurrency to 3–5, and accumulate results. The SDK has no built-in batching for delete/stop; you loop and call per-resource actions.

Region-scoped clients. An Ecs client with ecs.cn-hangzhou.aliyuncs.com can still accept a regionId of cn-beijing, but you should not rely on it. For multi-region work, create one client per region (keyed cache) and pass the matching endpoint. Discover regions once with describeRegions and cache the list.

Gotchas and Tips

Parameter casing is camelCase, and typos are silent. Request models are constructed from arrays; unknown keys are ignored, not rejected. new DescribeInstancesRequest(['RegionId' => 'cn-hangzhou']) will not set regionId and you will get a validation error from the API at best, an empty result at worst. Copy parameter names verbatim from the *Request class properties in vendor/. Add a PHPStan rule or a small assert in dev if you hit this twice.

Null-safe everything. Nearly every response property is optional and typed as nullable. $response->body->instances->instance is null when there are zero results — not an empty array. Always ?? [].

endpoint is required. If you omit it, the client either throws or routes to an unexpected host. There is no region-based endpoint auto-resolution you can trust here. Set it explicitly and derive it from the region (ecs.{region}.aliyuncs.com).

Catch TeaError, not generic exceptions. API errors surface as Tea\Exception\TeaError with ->code, ->message, and ->data (containing RequestId, Recommend). Common codes: Throttling, InvalidInstanceId.NotFound, IncorrectInstanceStatus, Forbidden.RAM. Log RequestId on every failure — Alibaba support requires it.

use Tea\Exception\TeaError;

try {
    $client->stopInstance($request);
} catch (TeaError $e) {
    Log::warning('ecs.stop.failed', [
        'code' => $e->getCode(),
        'message' => $e->getMessage(),
        'request_id' => $e->data['RequestId'] ?? null,
    ]);
}

Retry only on the right errors. Throttling, ServiceUnavailable, and 5xx are retryable. InvalidInstanceId.NotFound and IncorrectInstanceStatus are not — the latter usually means the instance is mid-transition; poll status and retry later at the job level, not the HTTP level.

Composer lockstep with other Alibaba SDKs. This package shares alibabacloud/darabonba-openapi with OSS, RDS, VPC, etc. If you use several, upgrade them together. Version skew in the shared runtime is the most common cause of "it worked yesterday" failures. Pin exact versions in composer.json and upgrade deliberately — this package regenerates frequently and model fields do change.

Autoloader size. The package contains thousands of generated model classes. composer dump-autoload -o helps; --classmap-authoritative helps more but increases deploy time. Do not disable PSR-4 optimization casually in production.

Never patch vendor/. It is generated from the OpenAPI spec and will be overwritten on the next composer update. If you need behavior changes, subclass Ecs or wrap it in your own EcsService with an interface — which also makes it mockable in tests, since the client itself is awkward to fake.

STS credentials expire. When using RAM role / STS tokens, the securityToken is short-lived. For long-running queue workers, resolve credentials per job from your token-refresh mechanism rather than caching the Ecs singleton forever — or rebuild the client when the token nears expiry.

Do not confuse package version with API version. V20140526 in the namespace is the ECS API version, frozen since 2014. The Composer package version increments with SDK regeneration. Both can be current.

Low community signal — budget for self-sufficiency. Two stars and zero dependents means no Stack Overflow corpus and no third-party examples. Your references are the generated src/Ecs.php, the src/Models/ classes, and Alibaba's official API docs. For anything ambiguous, read the request model — it is the most accurate documentation you have.

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.
skyraptor/chatter
edlugz/sasapay
abbasudo/artisan-route
mirvan/ippanel
ignibyte/aic-framework
glavweb/data-schema-bundle
glavweb/datagrid-bundle
tacticmedia/scim-server
uni-method/frame
neika-ai/sdk
adachsoft/php-code-style
pharaonic/laravel-notification-dependencies
beautinow/translug
dev-brainiac/bot-cloaked
octoberrain/html
octoberrain/extension
octoberrain/exception
octoberrain/contracts
adachsoft/api-version-bundle
cgv/localized-resource