Rob Rob -4 years ago 221
PHP Question

PHP Slim Get route placeholder in a container

Is it possible get the value of a route placeholder within a Slim container? I know I can access the placeholder by adding a third parameter to the request but I'd like to have it injected so I'm not assigning it on each request.

I've tried $app->getContainer('router') but I can't seem to find a method to actually pull the placeholder value.

Example:

$app = new Slim\App;

$c = $app->getContainer();

$c['Controller'] = function() {
$userId = // how do I get the route placeholder userId?
return new Controller($userId);
};

$app->get('/user/{userId}','Controller:getUserId');

class Controller {
public function __construct($userId) {
$this->userId = $userId;
}

public function getUserId($request,$response) {
return $response->withJson($this->userId);
}
}

Answer Source

Without some 'hacky' things this will not work because we have no access on the request object build by slim, while the controller get constructed. So I recommend you to just use the 3rd parameter and get your userid from there.

The 'hacky' thing would be todo the same, what slim does when you execute $app->run(), but if you really want todo this, here you'll go:

$c['Controller'] = function($c) {
    $routeInfo = $c['router']->dispatch($c['request']);
    $args = $routeInfo[2];
    $userId = $args['userId'];
    return new Controller($userId);
};

Note: slim3 also urldecoded this values so may do this as well urldecode($args['userId']) Source

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download