PHPackages                             komodohq/siesta - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [HTTP &amp; Networking](/categories/http)
4. /
5. komodohq/siesta

ActiveLibrary[HTTP &amp; Networking](/categories/http)

komodohq/siesta
===============

Traits mixin for consuming REST APIs

v0.1.4(10y ago)12.0k1MITPHPPHP &gt;=5.4.0

Since Jul 11Pushed 10y ago1 watchersCompare

[ Source](https://github.com/KomodoHQ/Siesta)[ Packagist](https://packagist.org/packages/komodohq/siesta)[ Docs](http://github.com/KomodoHQ/Siesta)[ RSS](/packages/komodohq-siesta/feed)WikiDiscussions master Synced 2d ago

READMEChangelog (5)Dependencies (4)Versions (6)Used By (0)

Siesta
======

[](#siesta)

Easily add API Consumption to your PHP Classes.

Siesta will add methods to consume your JSON REST API and convert the results to instances of your PHP models.

Installation
------------

[](#installation)

composer.json:

```
{
    "require": {
        "komodohq/siesta": "dev-master"
    }
}
```

```
$ composer install

```

Usage
-----

[](#usage)

```
class User {

    use Siesta\Siesta;

    private static $siestaConfig = [
            "url" => "http://localhost:9999",
            "endpoint" => "users"
        ];

    // constructor takes assoc array of properties
    function __construct($data) {
        $this->_id = $data['id'];
        $this->name = $data['name'];
    }
}

$users = User::find();
```

Methods
-------

[](#methods)

### `Siesta::find`

[](#siestafind)

```
User::find([$queryParams[, $options]]);

User::find();
User::find(["username" => "OiNutter"]);
User::find(["username" => "OiNutter"], ["endpoint" => "administrators"]);
```

Performs a GET request to `/` that returns a collection of items matching the supplied query parameters.

NB. This method is also used by the findOne method so be aware if you override this method it will also affect that method.

### `Siesta::findOne`

[](#siestafindone)

```
User::findOne([$queryParams[, options]]);

User:find();
User::findOne(["username" => "OiNutter"]);
User::findOne(["username" => "OiNutter"], ["endpoint" => "administrators"]);
```

Performs a GET request to `/{{endpoint}}` and returns the first result to match the supplied query parameters. Sets an additional `limit` parameter to 1 so if the API being consumed supports that it will limit the amount of responses returned and save work on your end.

### `Siesta::findById`

[](#siestafindbyid)

```
User::findById($id[, $options]);

User::findById(1);
User::findById(1, ["endpoint" => "administrators"]);
```

Performs a GET request to `/{{endpoint}}/{{this->id}}` and returns a single result with the matching id.

### `Siesta::create`

[](#siestacreate)

```
User::create($data[, $options]);

User::create(["username" => "Bob", "email" => "bob@komododigital.co.uk"]);
User::create(
    ["username" => "Bob", "email" => "bob@komododigital.co.uk"],
    ["endpoint" => "administrators"]
);
```

Performs a POST request to `/{{endpoint}}` with the supplied data and returns the newly created resource.

### `$siestaItem->update`

[](#siestaitem-update)

```
$user->update($data[, $options]);

$user->update(["location" => "Newcastle Upon Tyne"]);
$user->update(["location" => "Newcastle Upon Tyne"], ["endpoint" => "administrators"]);
```

Performs a PUT request to `/{{endpoint}}/{{this->id}}` with the supplied data and returns the updated resource. It will also update the local resource with any fields that have been updated on the server.

### `$siestaItem->save`

[](#siestaitem-save)

```
$user->save([$options]);

$user->save();
$user->save(["endpoint" => "administrators"]);
```

Performs a PUT request to `/{{endpoint}}/{{this->id}}` with the current resource and returns the updated resource. It will also update the local resource with any fields that have been updated on the server.

If the resource has not already been saved to the server (doesn't have an id set) this method will perform a POST request instead. The local object will then be updated with the newly created id.

NB. This method is also used by the update method so be aware if you override this method it will also affect that method.

### `$siestaItem->delete()`

[](#siestaitem-delete)

```
$user->delete([$options]);

$user->delete(["endpoint" => "administarots"]);
```

Performs a DELETE request to `/{{endpoint}}/{{this->id}}` and returns an associative array representing the HTTP response body returned from the server.

Customisation
-------------

[](#customisation)

### `Siesta::$siestaConfig`

[](#siestasiestaconfig)

To configure your class to use Siesta you need to add a `private static $siestaConfig` variable to your class. This is an `associative array` which can contain the following keys:

- `url` - The FQD of the API you are going to be interacting with. **Required**
- `endpoint` - The endpoint on the API that maps to the resource your class represents. Defaults to `''`.
- `idProperty`- The primary key field for your class. Can be different from the primary key on the API Response. Defaults to `id`.
- `resultField` - The property of the API response that contains the result of the query or action. Defaults to `result`
- `tokenField` - The `$_SESSION` key under which your oauth token is stored. Defaults to `SIESTA_OAUTH_TOKEN`.
- `requestContentType` - The body content type that is sent in PUT and POST requests. Defaults to `application/json`.

### `Siesta::populate`

[](#siestapopulate)

To change how a new model is created from the returned API data you will need to override the `populate` method. The default passes the returned data as an `associative array` to the class' constructor method.

```
public static function populate($item)
{
    return new static($item);
}
```

But say you wanted to pass the properties as individual arguments to the constructor, you could override it in your class definition so it looked like this:

```
public static function populate($item)
{
    $reflect  = new ReflectionClass($class);
    return $reflect->newInstanceArgs($item);
}
```

### `Siesta->toArray`

[](#siesta-toarray)

Siesta adds a `public` `toArray` method to your class. This is used to serialize the class for sending in a save request. The default merely calls `get_object_vars` on itself, like so:

```
public function toArray()
{
    return get_object_vars($this);
}
```

but you can override that to provide your own serialisation.

### `Siesta->setValue`

[](#siesta-setvalue)

Siesta adds a `public` `setValue` method which is used by the update and save methods to update properties based on the response from the server. The default just sets the property to the value.

```
public function setValue($property, $value)
{
    $this->$property = $value;
}
```

You can override this to perform any extra manipulation on the properties before setting them.

```
public function setValue($property, $value)
{
    if ($property == 'registered') {
        $this->$property = strtotime($value);
    } else {
        $this->$property = $value;
    }
}
```

Exceptions
----------

[](#exceptions)

### `SiestaGeneralException`

[](#siestageneralexception)

Base class for any general exceptions. Stores the response body which can be retrieved like so:

```
$e->getResponse();
```

### `SiestaClientException`

[](#siestaclientexception)

Exception class for HTTP error codes in the 400 range. Extends `SiestaGeneralException`.

### `SiestaServerException`

[](#siestaserverexception)

Exception class for HTTP error codes in the 500 range. Extends `SiestaGeneralException`.

Laravel
-------

[](#laravel)

If using Laravel you can omit the URL config variable for Siesta and it will look for `Config::get('api.url')` instead.

TODO
----

[](#todo)

- Improve Error Handling
- More Tests
- Tidy up tests

Tests
-----

[](#tests)

Run `composer install` to get the testing library.

Start the test API server

```
$ php -S localhost:9999 ./tests/index.php

```

Run the tests

```
$ bin\behat

```

Contributing
------------

[](#contributing)

- Code should conform to [PSR 2 Coding Standards](http://www.php-fig.org/psr/psr-2/).
- Keep pull requests to significant changes and additions. Minor typos and documentation additions should just be raised as issues.
- Ensure all unit tests pass, and if adding new functionality add unit tests for it and make sure they pass.
- We may not always accept pull requests if we feel they don't they are in line with the aims of the library or if we don't feel they add significant benefit. We will always try and explain our reasoning and are prepared to be convinced otherwise.
- Keep it polite ;)

###  Health Score

27

—

LowBetter than 49% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity18

Limited adoption so far

Community8

Small or concentrated contributor base

Maturity52

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~146 days

Total

5

Last Release

3737d ago

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/7881359?v=4)[Komodo Digital](/maintainers/KomodoHQ)[@KomodoHQ](https://github.com/KomodoHQ)

---

Top Contributors

[![OiNutter](https://avatars.githubusercontent.com/u/68246?v=4)](https://github.com/OiNutter "OiNutter (55 commits)")

---

Tags

apirest

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/komodohq-siesta/health.svg)

```
[![Health](https://phpackages.com/badges/komodohq-siesta/health.svg)](https://phpackages.com/packages/komodohq-siesta)
```

###  Alternatives

[xeroapi/xero-php-oauth2

Xero official PHP SDK for oAuth2 generated with OpenAPI spec 3

1054.3M14](/packages/xeroapi-xero-php-oauth2)[cybercog/youtrack-rest-php

YouTrack REST API PHP Client.

37149.2k3](/packages/cybercog-youtrack-rest-php)[onesignal/onesignal-php-api

A powerful way to send personalized messages at scale and build effective customer engagement strategies. Learn more at onesignal.com

34170.2k2](/packages/onesignal-onesignal-php-api)[ory/hydra-client

Documentation for all of Ory Hydra's APIs.

17435.9k](/packages/ory-hydra-client)[zenditplatform/zendit-php-sdk

PHP client for Zendit API

1204.3k](/packages/zenditplatform-zendit-php-sdk)[whatarmy/fedex-rest

New FedEx Rest API wrapper

2440.5k1](/packages/whatarmy-fedex-rest)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
