PHPackages                             tagged/rest - 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. tagged/rest

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

tagged/rest
===========

Easily create restful apis and services. Based on Klein.php

v0.13(12y ago)13501[1 issues](https://github.com/rdgoetz/TaggedRest/issues)MITPHPPHP &gt;=5.3.0

Since Feb 20Pushed 12y ago1 watchersCompare

[ Source](https://github.com/rdgoetz/TaggedRest)[ Packagist](https://packagist.org/packages/tagged/rest)[ Docs](https://github.com/rdgoetz/taggedrest)[ RSS](/packages/tagged-rest/feed)WikiDiscussions master Synced 3d ago

READMEChangelogDependencies (4)Versions (7)Used By (0)

Restful routing/controllers
===========================

[](#restful-routingcontrollers)

Tagged/Rest is a small framework for creating restful api's in object oriented controllers rather than callbacks. It comes with powerful validation from the json schema project, and api methods both respond to http requests and can be called internally as normal object methods. There's also a mechanism to dynamically generate documentation for all api endpoints for free, just hit the url with an OPTIONS request.

The framework is focused only on handling http requests, leaving the rest of the project for other frameworks or existing code.

Really, this is just a wrapper around [Klein](https://github.com/chriso/klein.php) that allows for easy construction of restful urls and controllers.

A url maps to a controller based on a routes mapping, and the controller handles the http request/response.

Routes
------

[](#routes)

A route looks something like **/owners/\[a:name\]/dogs**.

The value in square brackets is matched and passed to the controller as query parameters.

A request to **/owners/george/dogs?color=brown** to the route above becomes

```
name = george
color = brown

```

A route with a parameter as the last part of the url path is considered a resource route, and a route with a static name as the last part is a collection. Above, the dogs route would be a collection and photos a resource.

Routes support many features such as optional values and validation. See https://github.com/chriso/klein.php#routing for more about route syntax.

---

The router takes a parameter that is an array of routes mapped to a controller, like

```
$routes => array(
            "/login" => "login",
            "/health" => "health",
            # the scope operator allows for setting a specific method
            "/health/echo" => "health::showParams",
            #  a namespace URL. Children of this are appended.
            "/users/[i:userid]" => array(
                "/loginhistory" => "loginhistory",
                "/messages" => "messages",
                "/photos" => "photos",
                "/photos/[i:photoid]" => "photos"
            )
        )
```

where the key is the route path and the value a namespace. If instead of a string, the value is an array, then the routes in that array are nested under the parent path. The router also takes a parameter defining a route namespace and another one defining the controller namespace.

A special syntax allows for mapping to a specific method for that route that's not one of the defaults. If the right hand side looks like "controllerClass::methodName", then a POST to the route on the left side will be handled by that method. In the example above, a post to /health/echo will be handled by the method 'showParams()' in the health controller.

Here's an example using the routing array above. If the route namespace **/api/v1**, the controller namespace **/app/controllers**, then routes generated by the config above are:

```
/api/v1/login                                => /app/controllers/login.php
/api/v1/users/[i:userid]/loginhistory        => /app/controllers/loginhistory.php
/api/v1/users/[i:userid]/messages            => /app/controllers/messages.php
/api/v1/users/[i:userid]/photos              => /app/controllers/photos.php
/api/v1/users/[i:userid]/photos/[i:photoid]  => /app/controllers/photos.php

```

The http methods supported by each route are determined by looking at the controller. Routes are either handled as a collection or a resource. A resource acts on a single record (database row), and a collection acts on many records (database table). In the example above, requests to **/api/v1/users/\[i:userid\]/photos** would be handled by the controller as a collection, and **/api/v1/users/\[i:userid\]/photos/\[i:photoid\]** as a resource. This is determined by the convention of resource routes ending in an id/paramter (*/\[i:photoid\]*) and collections ending in the name of the collection (*/photos*).

Validation
----------

[](#validation)

Validation is done using a json schema validator. The query/form parameters are treated as a nested json structure. This structure comes from php's built in query deserialization. Query params like '?item\[key\]=value' are serialized as an array like `array( 'item' => array('key'=>'value'))`.

This is fed into a validator that ensures the query parameters are structured how the API expects. For more info on json schema syntax and options, check .

The schemas for each controller function are registered in the constructor.

Controllers
-----------

[](#controllers)

Controllers handle the http request. A handler method expects to be passed a stdClass object. The value returned by the method becomes the body of the http request.

The default mapping is below, but can be overridden. Methods not implemented become HTTP 405 errors when requested.

Every controller method is passed a response and request object. Check  for documentation.

HTTP methodController methodExpected actionGET (resource)fetch()get the requested item (no side effects)PUT (resource)update()update the requested item (idempotent)DELETE (resource)delete()delete the requested item (idempotent)GET (collection)index()used as an index function for simple urlsGET (collection)find()list all items matching the query (no side effects)POST (collection)create()create a new itemPUT (collection)bulkUpdate()update a set of items (idempotent)DELETE (collection)deleteAll()delete all items (idempotent)Note that there are two handlers for GET requests on a collection. This is just so that controller methods can have better names. Use find when the method is going to be returning a collection of data. Index is better used for responding to basic url's, like a health check or html page.

A controller may register as many methods as it likes to respond to the same http action, which is usesful for custom actions. Custom methods can be registered in the constructor. Also, multiple controllers may respond to the same route.

Controller example:

```
