nathggns / Scaffold

Lightweight PHP API Framework
Other
8 stars 2 forks source link

Class Based Interface #20

Open nathggns opened 12 years ago

nathggns commented 12 years ago

A popular usage model for api-first applications is to have a class based interface for their application.

<?php
$users = Scaffold::get('/users/nathaniel');
$user = Scaffold::post('/users', array(
    'username' => 'claudio',
    ...
));

I've got a few ideas for how to make this possible, but I'm posting it as an issue first to see what you think.

ClaudioAlbertin commented 12 years ago

Certainly a good idea as it avoids the overhead of HTTP requests. It should certainly be possible to provide request bodies ($_POST, etc.) and query parameters ($_GET) as an array, but also resources (the id of a user for example) should not be required to include in the URI. How's this:

$user = Scaffold::get('/users/:id', array('id' => 5));

But also a more object oriented approach should be considered, such as:

$user = $scaffold->users->get(5);
nathggns commented 12 years ago

I like being able to include the id in the data, but it should be possible to do both.

As for the object orientated way, the whole API should not be an object, because it isn't, it's a set of objects.

<?php
$users = Scaffold::resource('users');
$user = $users->get(5);
ClaudioAlbertin commented 12 years ago

I guess the object oriented approach doesn't work very well here anyway, as we would have to map the routes to object again. I don't like the idea of having to know how the API is constructed internally to use it. Let's just use the URI way and enable replacements in the URI to avoid requiring to concatenate everything yourself.

nathggns commented 12 years ago

Probably a good idea.

ClaudioAlbertin commented 12 years ago

As our routing system is very flexible, it will be easy to implement this. What we want is currently possible like this:

// GET
$request = Service::get('request', '/users/5', 'get');
$response = $router->run($request)->response->data;

// PUT
$request = Service::get('request', '/users/5', 'put');
$request->body = array('name' => 'Nathaniel Higgins');
$response = $router->run($request)->response->data;

// DELETE
$request = Service::get('request', '/users/5', 'delete');
$response = $router->run($request)->response->data;
nathggns commented 11 years ago

This probably wouldn't be ideal without namespacing though?

ClaudioAlbertin commented 11 years ago

Nothing is ideal without namespacing, but it certainly works without.

nathggns commented 11 years ago

The problem is, if the main site uses a framework, there will be a lot of clashing classes. This will have to wait until we successfully implement namespaces.