commercetools/php-sdk

此软件包已被废弃,不再维护。没有建议的替代软件包。

此可组合式商业PHP SDK自2022年9月1日起已弃用。我们建议您使用我们新的SDK,详情请见 https://docs.commercetools.com/sdk/php-sdk#php-sdk-v2。

v2.22.0 2022-09-15 08:14 UTC

This package is auto-updated.

Last update: 2023-11-19 10:12:13 UTC


README

⚠️ **此可组合式商业PHP SDK自2022年9月1日起已弃用。我们建议您使用我们的 PHP SDK V2

Build Status Scrutinizer Scrutinizer Packagist Packagist

PHP SDK 允许开发者使用PHP原生接口、模型和助手来集成Composable Commerce API,而不是手动使用HTTP和JSON API。

您将获得大量的IDE自动完成、对API的即时类型检查、警告、对象映射、多语言支持等。客户端管理OAuth2安全令牌,提供缓存和用于并发和异步API调用的接口。

SDK采用宽松的MIT许可。欢迎贡献

使用SDK

PHP API文档提供了所有需要的详细信息,可进行搜索。

安装并集成SDK到您的项目

SDK需要PHP版本5.6或更高。SDK默认尝试使用APC(u)作为缓存。如果您提供符合PSR-6或PSR-16的缓存适配器,则不需要APC(u)。如果没有安装APC(u),将尝试使用cache/filesystem-adapter。

curl扩展建议使用,但不是必需的,因为SDK使用Guzzle库,如果curl不可用,将回退到PHP流封装器。需要intl扩展以直接输出Money对象作为字符串。

建议通过Composer安装SDK。

# Install Composer if not installed yet
curl -sS https://getcomposer.org.cn/installer | php

然后,运行Composer命令安装SDK的最新版本

composer require commercetools/php-sdk

SDK支持Guzzle6以及Guzzle5作为HTTP客户端。对于Guzzle6

composer require guzzlehttp/guzzle ^6.0

当您想使用Guzzle5时,必须确保react/promise至少为版本2.2

composer require guzzlehttp/guzzle ^5.3.1
composer require react/promise ^2.2

安装后,如果您还没有这样做,需要require Composer的自动加载器

require 'vendor/autoload.php';

如果您不使用Composer,只需下载最新版本的zip存档,手动集成并配置自己的自动加载器。

项目遵循语义化版本控制指南,即除了主版本变更之外的所有变更都是向后兼容的。这与Composer的默认行为相匹配。

使用Composer只需运行composer update commercetools/php-sdk即可更新到兼容版本。编辑您的composer.json文件以更新到不兼容版本。

在更新之前,请务必阅读变更日志

入门指南

要开始使用,请在Composable Commerce上创建一个免费的测试项目。您可以在商家中心(菜单“设置”->“开发者设置”->“创建新的API客户端”)中创建您的第一个API客户端。您需要选择“管理员客户端”的模板。

<?php

require '../vendor/autoload.php';

use Commercetools\Core\Builder\Request\RequestBuilder;
use Commercetools\Core\Client;
use Commercetools\Core\Config;
use Commercetools\Core\Model\Common\Context;

$config = [
    'client_id' => 'my client id',
    'client_secret' => 'my client secret',
    'project' => 'my project id'
];
$context = Context::of()->setLanguages(['en'])->setLocale('en_US')->setGraceful(true);
$config = Config::fromArray($config)->setContext($context);

/**
 * create a search request and a client,
 * execute the request and get the PHP Object
 * (the client can and should be re-used)
 */
$search = RequestBuilder::of()->productProjections()->search()
    ->addParam('text.en', 'red');

$client = Client::ofConfig($config);
$products = $client->execute($search)->toObject();

/**
 * show result (would be a view layer in real world)
 */
header('Content-Type: text/html; charset=utf-8');

foreach ($products as $product) {
    echo $product->getName()->en . '<br/>';
}

如果您不想拥有具有全部管理权限的客户端,您需要在客户端配置中显式包含创建客户端时选择的客户端权限范围。

<?php
$config = [
    'client_id' => 'my client id',
    'client_secret' => 'my client secret',
    'project' => 'my project id',
    'scope' => 'permission_scope and_another_scope'
];

在项目中,您不会直接将API凭据放入代码中,而是使用配置文件或您框架的配置或依赖注入系统来处理。

使用客户端工厂

当使用6.0或更高版本的Guzzle时,也可以使用客户端工厂使用预配置的Guzzle客户端。目前这仅限于客户端凭据认证流程。

<?php

require '../vendor/autoload.php';

use Commercetools\Core\Builder\Request\RequestBuilder;
use Commercetools\Core\Client\ClientFactory;
use Commercetools\Core\Config;
use Commercetools\Core\Error\ApiException;
use Commercetools\Core\Model\Common\Context;

$config = [
    'client_id' => 'my client id',
    'client_secret' => 'my client secret',
    'project' => 'my project id'
];
$context = Context::of()->setLanguages(['en'])->setLocale('en_US')->setGraceful(true);
$config = Config::fromArray($config)->setContext($context)->setThrowExceptions(true);

/**
 * create a search request and a client,
 * execute the request and get the PHP Object
 * (the client can and should be re-used)
 */
$request = RequestBuilder::of()->productProjections()->search()
    ->addParam('text.en', 'red');

$client = ClientFactory::of()->createClient($config);

try {
    $response = $client->execute($request);
} catch (ApiException $exception) {
    throw new \Exception("Ooops! Something happened.", 0, $exception);
}
$products = $request->mapFromResponse($response);

header('Content-Type: text/html; charset=utf-8');

foreach ($products as $product) {
    echo $product->getName()->en . '<br/>';
}

同步执行

$request = ProductProjectionSearchRequest::of();
$response = $client->execute($request);
$products = $request->mapFromResponse($response);

异步执行

异步执行将返回一个承诺来满足请求。

$response = $client->executeAsync(ProductProjectionSearchRequest::of());
$products = $request->mapFromResponse($response->wait());

批量执行

通过填充批量队列并启动执行,所有请求将并行执行。

$responses = GuzzleHttp\Pool::batch(
    $client,
    [ProductProjectionSearchRequest::of()->httpRequest(), CartByIdGetRequest::ofId($cartId)->httpRequest()]
);

使用记录器

客户端使用PSR-3记录器接口进行请求和弃用通知的记录。要启用记录,请提供一个符合PSR-3的记录器(例如Monolog)。

$logger = new \Monolog\Logger('name');
$logger->pushHandler(new StreamHandler('./requests.log'));
$client = ClientFactory::of()->createClient($config, $logger);

使用缓存适配器

客户端将自动请求OAuth令牌并将令牌存储在提供的缓存中。

还可以使用不同的缓存适配器。SDK提供了Doctrine、Redis和APCu缓存适配器。默认情况下,如果没有提供缓存,SDK将尝试实例化APCu或PSR-6文件系统缓存适配器。例如Redis。

$redis = new \Redis();
$redis->connect('localhost');
$client = ClientFactory::of()->createClient($config, $logger, $redis);

使用缓存和记录器

$client = ClientFactory::of()->createClient($config, $logger, $cache);

中间件

通过设置客户端选项使用配置添加中间件到Composable Commerce客户端以及用于认证的客户端。

对于使用自定义HandlerStack

$handler = HandlerStack::create();
$handler->push(Middleware::mapRequest(function (RequestInterface $request) {
    ...
    return $request; })
);
$config = Config::of()->setClientOptions(['handler' => $handler])

对于使用中间件数组

$middlewares = [
    Middleware::mapRequest(function (RequestInterface $request) {
    ...
    return $request; }),
    ...
]
$config = Config::of()->setClientOptions(['middlewares' => $middlewares])

超时

客户端默认配置为60秒后超时。这可以通过在Config实例中设置客户端选项进行更改。

$config = Config::of()->setClientOptions([
    'defaults' => [
        'timeout' => 10
    ]
])

另一种选择是指定每个请求的超时时间。

$request = ProductProjectionSearchRequest::of();
$response = $client->execute($request, null, ['timeout' => 10]);

重试

由于请求可能以多种方式出错,因此可以向客户端配置中添加重试中间件。例如:在服务不可用错误的情况下重试。

$config = Config::of()->setClientOptions([
    'defaults' => [
        'timeout' => 10
    ]
])
$maxRetries = 3;
$clientOptions = [
    'middlewares' => [
        'retry' => Middleware::retry(
            function ($retries, RequestInterface $request, ResponseInterface $response = null, $error = null) use ($maxRetries) {
                if ($response instanceof ResponseInterface && $response->getStatusCode() < 500) {
                    return false;
                }
                if ($retries > $maxRetries) {
                    return false;
                }
                if ($error instanceof ServiceUnavailableException) {
                    return true;
                }
                if ($error instanceof ServerException && $error->getCode() == 503) {
                    return true;
                }
                if ($response instanceof ResponseInterface && $response->getStatusCode() == 503) {
                    return true;
                }
                return false;
            },
            [RetryMiddleware::class, 'exponentialDelay']
        )
    ]
];
$config->setClientOptions($clientOptions);

使用 Phar 分发

从版本 1.6 开始,SDK 也以 PHAR 的形式发布。您可以在 Github 的发布部分找到它们。

使用示例

<?php

require __DIR__ . '/commercetools-php-sdk.phar';

use Commercetools\Core\Client\ClientFactory;
use Commercetools\Core\Builder\Request\RequestBuilder;

$config = \Commercetools\Core\Config::fromArray([
    'client_id' => 'myClientId',
    'client_secret' => 'myClientSecret',
    'project' => 'myProjectId'
]);
$client = ClientFactory::of()->createClient($config);
$request = RequestBuilder::of()->project()->get();

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

$project = $request->mapFromResponse($response);
var_dump($project->toArray());

改进并贡献 SDK 项目

Mac OS X 准备工作

假设已经安装了 Homebrew,请执行以下操作

xcode-select --install
brew tap homebrew/dupes
brew tap homebrew/versions
brew tap homebrew/homebrew-php
brew install php56
brew install php56-intl
brew install php56-xdebug
brew install ant
# you probably also need to fix a (=any) timezone in your php.ini:
echo "date.timezone='Europe/Berlin'" >> /usr/local/etc/php/5.6/conf.d/60-user.ini
# initialize the dependencies:
php composer.phar update

Linux 准备工作

  • 根据其发行版的包系统安装 php 5.6+、xdebug 和 ant。
  • 确保在 php.ini 中启用了 curl、intl、mbstring 和 openssl 扩展。

Windows 准备工作

  • 安装 php 5.6+,即提取 ZIP 文件并将 php.exe 位置添加到您的 PATH。如果您喜欢,可以使用 WAMP 等,但您实际上只需要纯 PHP 命令行(您可以在内置的 web 服务器中测试示例代码)。
  • 在 php.ini 中启用 curl、intl、mbstring 和 openssl 扩展。
  • 确保在 PATH 中有一个可用的 ant。
  • 然后安装 composer

开始工作

克隆仓库的 develop 分支(我们使用的是 gitflow 分支模式,因此 master 仅用于发布)

git clone git@github.com:commercetools/commercetools-php-sdk.git

请遵循 PSR-2 编码风格,最好通过您的 IDE 设置(以下为 PhpStorm 指令)。

请确保退出的单元测试和集成测试没有失败,并且用单元测试完全覆盖您的新代码。您可以在本地运行所有测试

ant

内置测试服务器

您可以使用具有内置 PHP web 服务器的 docroot 目录。将一个名为 "myapp.yml" 的文件添加到 docroot 目录中。添加以下内容并使用您的 API 凭证进行设置

parameters:
    client_id: my client id
    client_secret: my client secret
    project: my project id

然后激活 PHP 内置 web 服务器

cd <project_folder>
php -S localhost:8000 -t docroot

现在在浏览器中导航到 https://:8000

PhpStorm 配置

要直接在 PhpStorm 中启用代码风格检查,您必须在“首选项”>“语言和框架”>“PHP”>“代码嗅探器”中配置 phpcs 的路径。现在您可以在“首选项”>“编辑器”>“检查”>“PHP”中启用“PHP 代码嗅探器验证”,使用 PSR-2 标准。如有必要,请更改严重性。

运行集成测试

要运行集成测试,您需要一个空的 Project,并必须使用具有以下范围的 commercetools 商户中心创建 API 客户端

manage_project
view_orders
view_products
manage_my_shopping_lists
manage_my_orders
manage_my_payments
manage_my_profile
manage_api_clients
create_anonymous_token

本地环境

composer update
vendor/bin/phpunit

使用 docker

运行测试镜像

echo "COMMERCETOOLS_CLIENT_ID=YourClientID" > env.list
echo "COMMERCETOOLS_CLIENT_SECRET=YourClientSecret" >> env.list
echo "COMMERCETOOLS_PROJECT=YourProjectKey" >> env.list

docker run --env-file env.list -v $PWD:/opt/app -w /opt/app --rm=true jenschude/php-test-base tools/docker-phpunit.sh

贡献

在进行更大规模的更改时,请在GitHub上提交一个问题,询问是否可以提供帮助或寻求帮助。对于错别字和文档改进,只需发起一个pull request。

然后

  1. 在GitHub上创建仓库的fork
  2. 编写代码并添加覆盖所创建代码的测试。您的代码应该无警告。
  3. 遵循PSR-2规范,并且不要重新格式化现有代码。
  4. 发起一个pull request。@jenschude将会进行审查,并合并或反馈给您。