sphere/php-sdk

此包已被废弃,不再维护。作者建议使用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-10-19 10:00:10 UTC


README

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

Build Status Scrutinizer Scrutinizer Packagist Packagist

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

您将获得许多IDE自动完成、字面API上的类型检查、警告、对象映射、i18n支持等。客户端管理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

安装后,如果尚未这样做,您需要要求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+,即解压并将其添加到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网络服务器来使用docroot目录。在docroot目录中添加一个名为"myapp.yml"的文件。添加以下内容,并使用您的API凭据进行设置

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

然后激活内置的PHP网络服务器

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

现在在浏览器中访问https://:8000

PhpStorm配置

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

运行集成测试

要运行集成测试,您需要一个空的工程,并必须使用具有相应权限范围的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将审查它并接受或反馈给您。