How can I get group name?

I have the following group of routes in my application:

$app->group('/admin', function () use ($app){
	$app->get("", function(){
		$page = new PageAdmin();
		$page->setTpl("main/main");
	});
});
$app->group('/user', function () use ($app){
	$app->get("", function(){
		$page = new PageUser();
		$page->setTpl("main/main");
	});
});

I want to define the value of a variable based on the group of these routes.

For example: if the group is “admin”, my variable will be equal to 1. If the group is “user”, my variable will be equal to 2.

How do I do this? I am using version 3 of the Slim Framework.

I’ve tried using middleware using $route-> getGroups () but my page gives an error and the result returned is much more complex than I need.

You could create separate middlewares for each group, one for admin and one for user.

Thanks for the answer! I tried to use middleware, but I was not very successful. I tried to do something as the documentation suggests and other problems happened. Could you give me an example or give me some more specific material?

I also put my question on StackOverflow in a little more detail and it seems that the most appropriate approach would be to use middleware, as you mentioned. The point is, I just can’t get out of place.

The link for my question is this one:

Thanks again for the answer!

We need an example of what you’re trying to do here. So throw in some real code where we can see how you use this variable and where.

I tried to assign the value to the variable after defining the group, but this approach did not work, because this value will always be that of the last group (because of the code reading flow). For example:

$app->group('/admin', function () use ($app){
    $dir = "root";

    $app->get("", function(){
        $page = new PageAdmin();
        $page->setTpl("main/main");
    });
});
$app->group('/user', function () use ($app){
    $dir = "all";

    $app->get("", function(){
        $page = new PageUser();
        $page->setTpl("main/main");
    });
});

In the above case, even if I am on a route in the “admin” group, the $dir variable will have the value “all”. If I comment out the line $dir = “all”; my application works normally, because the variable has not been replaced.

I tried to create middleware using the Slim Framework documentation itself as follows:

use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Message\ResponseInterface;
use \Rain\Tpl;

$slimSettings = array('determineRouteBeforeAppMiddleware' => true);

$slimConfig = array('settings' => $slimSettings);
$app = new \Slim\App($slimConfig);

$myMiddleware = function ($request, $response, $next) {

    $route = $request->getAttribute('route');
    $routeName = $route->getName();
    $groups = $route->getGroups();
    $methods = $route->getMethods();
    $arguments = $route->getArguments();

    print "Route Info: " . print_r($route, true);
    print "Route Name: " . print_r($routeName, true);
    print "Route Groups: " . print_r($groups, true);
    print "Route Methods: " . print_r($methods, true);
    print "Route Arguments: " . print_r($arguments, true);
};


$app->add($myMiddleware);

Using the code above, all information about groups, methods and arguments is displayed. As I said, this answer is much more complex than I believe it needs.

In addition, after commenting on the lines that print this information, my page simply stops working. So, even if I wanted to use them, I can’t, because from then on the following message starts to appear:

Slim Application Error

A website error has occurred. Sorry for the temporary inconvenience.

I believe that my problem is simple to be solved, but I admit I don’t have the necessary knowledge for that. I think I will be able to do what I need through middleware, but I just can’t seem to get it to work.

I don’t know if the comment I made below was in response to you, but that’s all I’ve tried to do so far.

I don’t see you trying to use that $dir anywhere, but will try to help you anyway.

You seem to be using Slim 3 so the following code is for same version. The code below should help you out and also carefully read the docs as this all is explained there pretty well http://www.slimframework.com/docs/v3/concepts/middleware.html.

$adminMiddleware = function ($request, $response, $next) {
    $request = $request->withAttribute('role', 'admin');

    return $next($request, $response);
};

$userMiddleware = function ($request, $response, $next) {
    $request = $request->withAttribute('role', 'user');

    return $next($request, $response);
};

$app->group('/admin', function () use ($app) {
    $app->get('/', function($request) {
        $role = $request->getAttribute('role');

        // $role is 'admin'
    });
})->add($adminMiddleware);

$app->group('/user', function () use ($app) {
    $app->get('/', function($request) {
        $role = $request->getAttribute('role');

        // $role is 'user'
    });
})->add($userMiddleware);

Thanks a lot for the help!

Seeing your code, another question arose: is it possible to get the $request data in the group instead of doing it for each route?

That is: instead of doing “$role = $request-> getAttribute(‘role’)” on each route, do this in the group? Something like:

$app->group('/admin', function () use ($app) {

	$role = $request->getAttribute('role');

	$app->get('/', function($request) {
		// do something
	});
})->add($adminMiddleware);

No you cannot do that, as the request object is not available there. Also I would suggest to use controller classes where your suggestion wouldn’t work even if the request object was there: http://www.slimframework.com/docs/v3/objects/router.html#container-resolution

I really appreciate the help. This made me better understand how to work with middleware.

The point is that accessing the request object on each route does not help me much. The value of the variable is arbitrary for each group, and not for each route, you know?

I could do this in a simpler way, assigning the value to the variable on each route, instead of using middleware.

Anyway, I thank you so much for your help and your patience. I am already reading the material you gave me on the link and I will continue looking for a way to deal with this problem.

Thank you very much!!!

There’s not really any difference by using the way you want it and using middleware. Inside route you would like to use lets say $dir, but now you just use $request->getAttribute('dir') instead. This solves your problem completely and you don’t need to assign a new variable for the value if you don’t want to.

Depending what you’re trying to do, you could also just simply use the app settings for the values:

$config = [
    'settings' => [
        'dir' => [
            'admin' => 'foo',
            'user' => 'bar',
        ],
    ],
];

$app = new \Slim\App($config);

$app->get('/', function ($request, $response, $args) {
    $dir = $this->get('settings')['dir']['admin'];
    // ...
});