tystr / rest-orm
一个简单的类似ORM的库,通过RESTful API处理对象持久化。
v0.6.0
2017-07-17 23:01 UTC
Requires
- php: >=7.0
- doctrine/annotations: ^1.2
- guzzlehttp/guzzle: ^6.1
- jms/metadata: ^1.5
- jms/serializer: ^1.0
- nocarrier/hal: ^0.9.11
Requires (Dev)
- fabpot/php-cs-fixer: ^1.10
- phpunit/phpunit: ~6.0
This package is not auto-updated.
Last update: 2024-09-14 17:48:25 UTC
README
注意:从v0.6.0
版本开始,此库依赖于PHP 7.x
。
一个简单的类似ORM的包,用于使用RESTful API处理对象持久化。
安装
使用composer安装tystr/rest-orm
# composer.phar require tystr/rest-orm:~0.1
配置
对于您的每个模型,您需要添加映射配置并设置一个Repository
实例。
映射
RestOrm提供了2个必须在每个模型上使用的注解
@Resource
这配置了在生成URL时使用的REST资源名称。@Id
这配置了用作标识符的属性。
数据通过JMS Serializer注入到模型中。有关如何为您的模型添加映射的信息,请参阅[文档](http://jmsyst.com/libs/serializer/master/reference)。
<?php use Tystr\RestOrm\Annotation\Resource; use Tystr\RestOrm\Annotation\Id; use JMS\Serializer\Annotation\Type; /** * @Resource("blogs") */ class Blog { /** * @Id * @Type("integer") */ protected $id; /** * @Type("string") */ protected $title; /** * @Type("string") */ protected $body; /** * @Type("datetime") */ protected $lastModified; // ... Accessor methods }
配置Repository
现在您的模型已经映射,您需要为每个模型配置一个Tystr\RestOrm\Repository\Repository
实例。
首先,配置用于向您的API发出请求的guzzle客户端
// Configure any auth headers when instantiating the guzzle client. These will be passed in each request. $headers = [ 'Authorization' => 'Token 23a65de8ea1f2b52defea12c0d7a9c11' ]; $client = new GuzzleHttp\Client(['headers' => $headers]);
接下来,设置RequestFactory
$urlGenerator = new Tystr\RestOrm\UrlGenerator\StandardUrlGenerator('https://example.com/api'); $format = 'json'; // either 'json' or 'xml' $requestFactory = new Tystr\RestOrm\Request\Factory($urlGenerator, $format);
现在实例化一个Response Mapper。RestOrm目前提供两种类型的response mapper
Tystr\RestOrm\Response\StandardResponseMapper
用于基本的JSON序列化和反序列化Tystr\RestOrm\Response\HalResponseMapper
用于HAL格式的API
$responseMapper = new Tystr\RestOrm\Response\StandardResponseMapper();
最后,为每个模型实例化一个Repository类
// Instantiate a repository. $class = 'Your\Project\Blog\Post'; $postRepository = new Tystr\RestOrm\Repository\Repository($client, $requestFactory, $responseMapper, $class);
用法
Tystr\RestOrm\Repository\RepositoryInterface
目前提供了4个基本方法来与您的模型交互
save($model)
findOneById($id)
findAll()
remove($model)