Robert Brax
Robert Brax

Reputation: 7318

Proper way to access the container from a class not in a slim controller

I have a regular php class outside of a controller, so it doesn't benefit from automatic injection of container. I need to access the response object from that class, and I guess I should get it from the container. What's the proper way to access it ? Just pass it as argument so the outside class can use it ? Is there a better way ?

Upvotes: 2

Views: 825

Answers (2)

Georgy Ivanov
Georgy Ivanov

Reputation: 1579

If you need to send a subrequest, Slim provides such functionality. Use it carefully though, as in some situations its result is not obvious.

<?php
class MySortOfOutsideClass
{
    /**
     * If you need to send a subrequest, you have to access application instance,
     * so let's inject it here.
     */
    public function __construct(\Slim\App $app)
    {
        $this->$app = $app;
    }

    /**
     * Method that makes a subrequest, and returns the result of it.
     */
    public function myMethod()
    {
        if ($subRequestIsRequired) {
            return $this->app->subRequest('GET', '/hello');
        }
    }
}

Upvotes: 0

jmattheis
jmattheis

Reputation: 11135

You need to use middleware for that because the response object is immutable so "changing" it will not update the response which will be used by slim.

$app->add(function($request, $response, $next) {
    if($shouldRedirect === true) {
        return $response->withRedirect('myurl'); // do not execute next middleware/route and redirect
    }
    return $next($request, $response); // execute next middleware/ the route
}); 

For more information about middleware have a look at this.

Upvotes: 1

Related Questions