dlinsmeyer / api-response-bundle

一个用于简化构建可维护API响应的Symfony2包。

v0.0.1 2014-08-21 21:20 UTC

This package is not auto-updated.

Last update: 2024-09-24 01:58:28 UTC


README

  1. 安装

要使用Composer安装API包,只需将以下内容添加到您的composer.json文件中

// composer.json
{
    // ...
    require: {
        // ...
        "dlinsmeyer/api-response-bundle": "dev-master"
    }
}
$ php composer.phar update

现在,Composer将自动下载所有必需的文件,并为您安装它们。接下来,您只需更新您的AppKernel.php文件,并注册新的包。

<?php

// in AppKernel::registerBundles()
$bundles = array(
    // ...
    new DLinsmeyer\Bundle\ApiBundle\DLinsmeyerApiBundle(),
    // ...
);
  1. 配置

###通过Symfony 无需额外配置。应用应正确检测此包中的所有配置。

###通过Silex 由于Silex中的包仅仅是包,我们需要进行一些手动服务配置。具体来说,在本例中,针对我们的序列化器。

  1. 引入
  2. 将以下内容添加到您的Silex引导文件中
    /**
     * since we can't load bundles proper, we need to register
     * the custom types that would be handled via our serializer service here
     */
    $callable = Pimple::protect(
        function(\JMS\Serializer\Handler\HandlerRegistry $handlerRegistry) {
            $handlerRegistry->registerSubscribingHandler(new \DLinsmeyer\Bundle\ApiBundle\Serializer\Handler\MixedTypeHandler());
        }
    );
    $application->register(
        new JDesrosiers\Silex\Provider\JmsSerializerServiceProvider(),
        array(
            "serializer.srcDir" => __DIR__ . "/vendor/jms/serializer/src",
            "serializer.configureHandlers" => $callable,
        )
    );
  1. 用法

随着SerializationAdapterInterface的引入,调用者可以利用响应构建器进行更多操作。

###JMS序列化器 如果没有其他配置,默认将使用JMS序列化器。

/**
 * @Inject("acme.repository.document")
 *
 * @var DocumentRepository
 */
private $documentRepository;

/**
 * @Inject("api_response_builder")
 *
 * @var ResponseBuilderInterface
 */
private $responseBuilder;

//...

/**
 * Search for documents
 *
 * @Route("/api/v{version}/documents/search/{query}.{_format}", name="acme_api_document_search")
 *
 * @param string $version
 * @param string $query
 *
 * @return JsonResponse
 */
public function searchAction($version, $query)
{
    $documents = $this->documentRepository->search($query);
    $this->responseBuilder->setVersion($version)
                          ->setFormat($this->getRequest()->getRequestFormat());

    if($someLogicCondition) {
        $this->responseBuilder->setSuccess(true)
                              ->setData($myLogicData);
    } else {
        $errors = $this->getErrors();
        $this->responseBuilder
            ->setSuccess(false)
            ->setMessage("Logic condition failed")
            ->setErrors($errors);
    }

    return $this->responseBuilder->buildResponse();

    return $response;
}

###JSON序列化器 要使用json_encode序列化,您需要更改配置

d_linsmeyer_api:
    api_response_serializer: api_response_serializer.json

注意: 默认情况下,此序列化器忽略所有与上下文相关的数据,例如版本、组等。只有响应模型将被编码。

除此之外,请参考上面的代码示例使用方法

  1. 扩展

###覆盖MixedTypeHandler 如果需要,您可能需要扩展MixedTypeHandler类。在这种情况下,请执行以下操作。

####创建覆盖类 创建一个扩展MixedTypeHandler的类。例如:

<?php

namespace YourVendor\YourBundle\Serializer\Handler;

use DLinsmeyer\Bundle\ApiBundle\Serializer\Handler\MixedTypeHandler as BaseMixedTypeHandler;

/**
 * Overrides the default Mixed type to
 * do something custom
 */
class MixedTypeHandler extends BaseMixedTypeHandler
{
    /**
     * Overrides the core type determinance to point some of our Document/Entity files
     * to their models
     *
     * @inheritdoc
     */
    protected function determineType($value)
    {
        $calcualtedType = parent::determineType($value);

        //do some custom logic

        return $calcualtedType;
    }
}

####覆盖服务 在您的调用库的服务配置文件中,执行以下操作

dlinsmeyer_api.serializer.handler.mixed_type:
    class: YourVendor\YourBundle\Serializer\Handler\MixedTypeHandler
    tags:
        - { name: jms_serializer.subscribing_handler }

###创建自定义序列化器 默认情况下,此库自带JMS和json_encode()序列化。要支持其他序列化器,请执行以下操作

  1. 创建一个扩展SerializerAdapterInterface的类

  2. 为该类创建一个服务定义。

  3. 在您的配置中,定义以下内容

    d_linsmeyer_api:
        api_response_serializer: %YOUR_SERIALIZER_SERVICE_REFERENCE%