tystr / rest-orm
A simple ORM-like library handling object persistence with a RESTful API.
Installs: 1 825
Dependents: 1
Suggesters: 0
Security: 0
Stars: 7
Watchers: 2
Forks: 3
Open Issues: 1
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-12-21 19:10:56 UTC
README
Note: as of v0.6.0
this library depends on PHP 7.x
.
A simple ORM-like package for handling object persistence using a RESTful API.
Installation
Install tystr/rest-orm
with composer:
# composer.phar require tystr/rest-orm:~0.1
Configuration
For each of your models you need to add mapping configuration and set up a Repository
instance.
Mapping
RestOrm provides 2 annotations which must be used on each model:
@Resource
This configures the name of the rest resource to use when generating urls.@Id
This configures the property to use as the identifier.
Data is hydrated into the models using JMS Serializer. See the documentation here for information on how to add mapping for your models.
<?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 }
Configure the Repository
Now that your models are mapped, you need to configure a Tystr\RestOrm\Repository\Repository
instance for each of your
models.
First, configure the guzzle client that will be used to make request to your API:
// 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]);
Next, set up the 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);
Now instantiate a Response Mapper. RestOrm currently provides 2 types of response mappers:
Tystr\RestOrm\Response\StandardResponseMapper
for basic JSON serialization/deserializationTystr\RestOrm\Response\HalResponseMapper
for HAL-formatted APIs
$responseMapper = new Tystr\RestOrm\Response\StandardResponseMapper();
Finally, instantiate a Repository class for each of your models:
// Instantiate a repository. $class = 'Your\Project\Blog\Post'; $postRepository = new Tystr\RestOrm\Repository\Repository($client, $requestFactory, $responseMapper, $class);
Usage
The Tystr\RestOrm\Repository\RepositoryInterface
currently provides 4 basic methods for interacting with your models:
save($model)
findOneById($id)
findAll()
remove($model)