Not sure if this is possible or not but I’d like to get the value of a route placeholder in a container. Can this be done?
Example:
$c = $app->getContainer();
$c['Controller'] = function() {
$userId = $params['userId']; // how do I get the route placeholder value here?
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);
}
}
I did get an answer on Stack Overflow and while it does work, it is a bit hacky as mentioned by the user who answered the question. Probably something that a container doesn’t need to deal with in the first place.
$c['Controller'] = function($c) {
$routeInfo = $c['router']->dispatch($c['request']);
$args = $routeInfo[2];
$userId = $args['userId'];
return new Controller($userId);
};
If I were to use it:
$app = new Slim\App;
$global = new Slim\Container;
$global['routeParam'] = function() use ($app) {
return function ($name) use ($app) {
$c = $app->getContainer();
$placeholders = $c['router']->dispatch($c['request']);
return $placeholders[2][$name];
};
};
// route file
$c = $app->getContainer();
$c['Controller'] = function() use ($global) {
$routeParam = $global->routeParam;
return new Controller($routeParam('userId'));
};
$app->get('/user/{userId}','Controller:getUserId');