2 minutes API with Siler and RedBeanPHP

Leo Cavalcante
2 min readFeb 14, 2017

--

Zero config. Zero boilerplate. Zero unnecessary stuff.

Siler is github.com/leocavalcante/siler
RedBeanPHP is github.com/gabordemooij/redbean

Let’s start!

Make a new directory and enter it

λ mkdir siler-n-redbean-rocks && cd siler-n-redbean-rocks

Bring the kids to the playground:

λ composer require leocavalcante/siler dev-master \
&& composer require gabordemooij/redbean dev-master

Let’s type!

Create an index.phpfile.

<?phprequire_once __DIR__.'/vendor/autoload.php';use Siler\Route;
use RedBeanPHP\Facade as R;
R::setup('sqlite:dbfile.db');
Route\resource('/beers', 'api/beers');

Simple like that

It requires Composer’s auto loader, setups RedBean to use SQLite (awesome for testing and prototyping) and declares a new Siler resource. Actually Siler avoids maintaining any kind of state so there is no such thing like aSiler\Resource, it’s a simple function call that does some magic:

Yet another Rails-like implementation

| Verb   | URI              | File        |
| GET | /beers | index.php |
| GET | /beers/create | create.php |
| POST | /beers | store.php |
| GET | /beers/{id} | show.php |
| GET | /beers/{id}/edit | edit.php |
| PUT | /beers/{id} | update.php |
| DELETE | /beers/{id} | destroy.php |

You probably already got that! But have we mapped the /beers URI path to what? Well, to files inside the api/beers directory.

Siler’s philosophy is to work with flat PHP files and functions as first-class citizens.

Let’s keep going

λ mkdir api && mkdir api/beers && touch api/beers/index.php

And here are the contents of api/beers/index.php :

<?phpuse RedBeanPHP\Facade as R;
use Siler\Http\Response;
$beers = R::findAll('beer'); // in the planetResponse\json($beers)
and exit; // wtf?

Yeah! We kept it simple

But will this work? We haven’t created a beer table or some sort of migration for that. This Response\json() thing will already output proper headers and encoded JSON values?

Yes.

λ php -S localhost:80 -t .

Now head to: http://localhost/beers
You have never been so amazed about an empty JSON array, I know…

No weird MVC stuff, no weird ORM configs. It just works!

Should I continue this post? How to get POST/PUT data?
Leave some comments!

--

--