Accessing attributes in a controller


I am building a API, and want to use controllers for my routes.

So a route will look like this:

$this->get('/account', 'MyController:foobar');

The MyController is extending a class called BaseController. In that file I have the following constructor:

class BaseController
    private $request;
    private $response;

    public function __construct($app)
        $this->request = $app->request;
        $this->response = $app->response;

Now, I can use $this->response to return, and I can get user data with $this->request->getParsedBody().

But I cannot figure out how to access the variables in the URL: /foo/bar/{user_id}. Using functions we got the $args variable, but I don’t want to have to use ($request, $response, $args) in every function in my controllers, if I can get access to it on the BaseController.

From reading the manual I thought I could use the getAttribute-function on the request-object, but no…

$route = $app->request->getAttribute('route');

This returns NULL. getAttributes returns an empty array.

What am I doing wrong here? Am I going about this the wrong way?


It’s a better idea to have

($request, $response, $args) 

on every route callback on your controllers.
The Request and Response from container ($app->request will get from container) should NEVER be used because they are never updated and they will be removed from container on the next Slim major version.
So you can only trust on $request and $response from function arguments, cause they will be always updated.

If you don’t want $args you could use:

//URL: /foo/bar/{user_id}

Thank you for clearing that up - I will drop my approach and do it the correct way :slight_smile:

Thanks, your answer also solved my question .

My new puzzle is how slim is done so that each method in the controller can get the $ request $ response in the form of this parameter?

Can you help me ?

I don’t know if you’ve discovered this yet, but part of the magic comes from here: MiddlewareAwareTrait :slight_smile: