Rob
Rob

Reputation: 1860

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);
    }
}

Upvotes: 1

Views: 968

Answers (2)

jmattheis
jmattheis

Reputation: 11135

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

Upvotes: 3

Simon Müller
Simon Müller

Reputation: 451

create a container wrapper and a maincontroller then extend all your controller from your maincontroller, then you have access to the container.

here is how i solved this problem:

https://gist.github.com/boscho87/d5834ac1ba42aa3da02e905aa346ee30

Upvotes: 1

Related Questions