user2302052
user2302052

Reputation:

PHP Slim - how to have multiple app objects for different routes?

Is it possible to have multiple Slim application objects for different sections/routes of a website.

For example:

I already tried modifing Apache's .htaccess using:

RewriteRule ^api front_controller_api.inc.php [QSA,L]
RewriteRule ^admin-panel front_controller_admin.inc.php [QSA,L]

...but this seems to break Slim's routing principles because Slim thinks that /api and /admin-panel are part of the request URI. It would be much easier to have different app objects with different configurations, middlewares etc. for each section of a page.

Any idea?

Upvotes: 1

Views: 1250

Answers (2)

Martin
Martin

Reputation: 3114

I don't know if that's the correct way to do it, but you try a folder structure like this:

public/
|-> api/
    |-> index.php
    |-> .htaccess
|-> admin-panel/
    |-> index.php
    |-> .htaccess

UPDATE:

I "investigated" some more and came up with another solution:

public/
|-> .htaccess
|-> admin-panel.php
|-> api.php

.htaccess:

RewriteEngine On

# Some hosts may require you to use the `RewriteBase` directive.
# If you need to use the `RewriteBase` directive, it should be the
# absolute physical path to the directory that contains this htaccess file.
#
# RewriteBase /

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^admin-panel/ admin-panel.php [QSA,L]
RewriteRule ^api/ api.php [QSA,L]

UPDATE 2:

With this solution you have to group everything to '/admin-panel' or '/api' in your route defintion.

Upvotes: 2

Davide Pastore
Davide Pastore

Reputation: 8738

You can do it in a easy way using groups:

$app->group('/api', function () use ($app){
    //Your api scope
    $app->myCustom = "my custom";

    $app->get('/', function () use ($app) {
        echo $app->myCustom;
    });

});

//Your amazing middleware.
function adminPanelMiddleware() {
    echo "This is my custom middleware!<br/>";
}


$app->group('/admin-panel', 'adminPanelMiddleware', function () use ($app){
    //Your admin-panel scope
    $app->anotherCustom = "another custom";

    $app->get('/', function () use ($app) {
        echo $app->anotherCustom;
    });
});

Upvotes: 0

Related Questions