Lionel
Lionel

Reputation: 2029

SLIM API: Multiple/Alternative routes for same action

We are building an API using the SLIM framework. Within our API hierarchy, some specific actions will be available with multiple paths. Here is an example:

$app->get('/surveys/:sid/contacts/:cid', function ($sid, $cid) use ($user) {
    // Do stuff
});

OR

$app->get('/contacts/:cid/surveys/:sid', function ($cid, $sid) use ($user) {
    // Do same stuff
});

We have already seen some approaches (e.g. Multiple routes with the same anonymous callback using Slim Framework) and were able to do this by referencing the anonymous function.

$app->get('/surveys/:sid/contacts/:cid', $ref = function ($sid, $cid) use ($user) {
    // Do stuff
});

AND

$app->get('/contacts/:cid/surveys/:sid', $ref); // Calls the same stuff, but with different order of arguments (wrong)

But how can we handle the changing order of passed arguments ("$sid, $cid" and "$cid, $sid")?

Thank you!


Thank you Andrew Smith for your answer! We will use a slightly different implementation:

function doStuff($user, $sid, $cid) {
    // Do stuff
}

$app->get('/surveys/:sid/contacts/:cid', function ($sid, $cid) use ($user) {
    doStuff($user, $sid, $cid);
});

$app->get('/contacts/:cid/surveys/:sid', function ($cid, $sid) use ($user) {
    doStuff($user, $sid, $cid);
});

Upvotes: 0

Views: 1247

Answers (1)

Andrew Smith
Andrew Smith

Reputation: 1851

Since you are using the same function, there isn't really a way of doing this besides creating another function that would call the first function. See example below.

<?php

function firstFunction ($sid, $cid) {
    // Do stuff
};

function secondFunction ($cid, $sid) {
    return firstFunction($sid, $cid);
};

$app->get('/surveys/:sid/contacts/:cid', 'firstFunction');

$app->get('/contacts/:cid/surveys/:sid', 'secondFunction');

Upvotes: 2

Related Questions