klein/klein.php

Alias a URI for API versioning

Opened this issue · 2 comments

I want to "alias" my API endpoints so developers using my API don't get stuck on 1.0.

Example routes:

- [{ method: POST }, { uri: "/api/1.0/games/documents" }, { class: [Main\Controllers\ApiGameCouchDbController, documents_create] }]

- [{ method: GET }, { uri: "/api/1.0/games/documents/id/[*:id]" }, { class: [Main\Controllers\ApiGameCouchDbController, documents_id_read] }]

- [{ method: GET }, { uri: "/api/1.0/games/documents/find/gameid/[*:gameid]" }, { class: [Main\Controllers\ApiGameCouchDbController, documents_find_game_id_read] }]

Is there an easy way to alias /api/games/documents/ to /api/1.0/games/documents/ so I don't have to duplicate every route?

Thanks

$klein->with('/api', resolveApiV1());
$klein->with('/ap/v1', resolveApiV1());

function resolveApiV1() use ($klein) {
    $klein->respond('GET', '/?', function ($request, $response) {
        // ...
    });
    $klein->respond('GET', '/user/[:id]', function ($request, $response) {
        // ...
    });
}

Like that?

Thanks for the late reply. I could still use this. Does that work with PHP 5.4?

Right now, I'm just duplicating the routes in the YAML file, close to what I listed above.

- [{ method: POST }, { uri: "/api/games/documents" }, { class: [Main\Controllers\ApiGameCouchDbController, documents_create] }]
- [{ method: POST }, { uri: "/api/1.0/games/documents" }, { class: [Main\Controllers\ApiGameCouchDbController, documents_create] }]

I'm using a config.yml file, so I can't use functions in there. This would start a split in configuration.

I'd have to include some php file before my YAML file if I wanted to go this route.