# Route and Middleware Strategies

**URL:** <https://discourse.slimframework.com/t/route-and-middleware-strategies/1291>\
**Category:** Questions\
**Created:** [March 19, 2017, 3:47am UTC](https://discourse.slimframework.com/t/route-and-middleware-strategies/1291 "2017-03-19T03:47:21Z")\
**Posts on this page:** 5\
**Page:** 1

<div class="post-metadata">

**Author:** ![LosLobos](https://yyz2.discourse-cdn.com/flex030/user_avatar/discourse.slimframework.com/loslobos/32/142_2.png) [@LosLobos](https://discourse.slimframework.com/u/LosLobos)\
**Post date:** [March 19, 2017, 3:47am UTC](https://discourse.slimframework.com/t/route-and-middleware-strategies/1291/1 "2017-03-19T03:47:21Z")

</div>

Hello !

Currently I using Container Resolution on my Controllers and I was able to “extend” the Routing Strategy by modifying **RequestResponse.php**.

Code Example:

```
/**
 * Default route callback strategy with route parameters as an array of arguments.
 */
class RequestResponse implements InvocationStrategyInterface
{
    /**
     * Invoke a route callable with request, response, and all route parameters
     * as an array of arguments.
     *
     * @param array|callable $callable
     * @param ServerRequestInterface $request
     * @param ResponseInterface $response
     * @param array $routeArguments
     *
     * @return mixed
     */
    public function __invoke(
        callable $callable,
        ServerRequestInterface $request,
        ResponseInterface $response,
        array $routeArguments
    ) {
        foreach ($routeArguments as $k => $v) {
            $request = $request->withAttribute($k, $v);
        }

        ---------------------------- HERE IS THE CHANGE!!! ------------------------

        if (!$callable instanceof Closure && $callable[0] instanceof BaseController) {
            
            $controller = $callable[0];

            $controller($request, $response, $routeArguments);
        }

   ---------------------------- END OF CHANGE ------------------------

        return call_user_func($callable, $request, $response, $routeArguments);
    }

```

The idea behind this is to my Controller process all Slim Data ( Using my Parsers ) and to give my ControllerBase more control over the PSR Objects beforehand. **( Give me thoughts about this or if this is a bad practise at all )**

Its a simple trick to pass the PSR objects and arguments directly to my Controller, instead of calling in each method of the class **parent\_\_invoke();** and keep the normal call to the method.

Example of this usage:

```
// Route Controller Classes extends from BaseController.
// This could be also registerUser(){} without the PSR Objects.
// return Slim Response Object
function registerUser(Request $request, Response $response, Array $args){
    // Method from my Controller that returns a formated type of data using Request Body for my own purposes.
    $data = this->getRequestBody();

    return $this->getResponse();
}

```

The thing is that Middlewares does not follow this RequestResponse Strategy and I would like to do the same to my Middlewares ( Yes I use a MiddlewareController ).

At the moment I have to call **parent\_\_invoke(request,response)** at the top of my middleware method.

Example:

```
// Middlewares classes extends from BaseController
function middleware(Request $request, Response $response){

     // Don't wanna call that.
    // parent__invoke($request,$response);

   // Do Stuffs....

}

```

I would like to understand where the Strategy is invoked so I can learn how to extend Middlewares functionality to my purposes.

Thanks in Advance,  
LosLobos.

---

<div class="post-metadata">

**Author:** ![MathMarques](https://yyz2.discourse-cdn.com/flex030/user_avatar/discourse.slimframework.com/mathmarques/32/501_2.png) [@MathMarques](https://discourse.slimframework.com/u/MathMarques)\
**Post date:** [March 23, 2017, 6:26pm UTC](https://discourse.slimframework.com/t/route-and-middleware-strategies/1291/2 "2017-03-23T18:26:44Z")

</div>

Slim`s Invocation Strategy is only used for the [route callable](https://github.com/slimphp/Slim/blob/3.x/Slim/Route.php#L336).

So Slim will execute: App Level Middlewares -\> Route Level Middlewares -\> and then use the Strategy to invoke your Route Callable

---

<div class="post-metadata">

**Author:** ![LosLobos](https://yyz2.discourse-cdn.com/flex030/user_avatar/discourse.slimframework.com/loslobos/32/142_2.png) [@LosLobos](https://discourse.slimframework.com/u/LosLobos)\
**Post date:** [March 24, 2017, 7:46am UTC](https://discourse.slimframework.com/t/route-and-middleware-strategies/1291/3 "2017-03-24T07:46:45Z")

</div>

I looked up the code and this line that you marked up caught my attention.

> /\*\* @var InvocationStrategyInterface $handler \*/  
> $handler = isset($this-\>container) ? $this-\>container-\>get(‘foundHandler’) : new RequestResponse();

I’m adding these changes directly to Slim but this line suggests that I can use the Container to override the current InvocationStrategyInterface, is this correct ?

Can I just write my own InvocationStrategy that implements InvocationStrategyInterface and on the app initialization insert on Container my own Handler ?

Also this doesn’t change the way that Middlewares are executed right ? If I would like to make Slim execute my Middleware’s invoke method, how I would do that ?

---

<div class="post-metadata">

**Author:** ![MathMarques](https://yyz2.discourse-cdn.com/flex030/user_avatar/discourse.slimframework.com/mathmarques/32/501_2.png) [@MathMarques](https://discourse.slimframework.com/u/MathMarques)\
**Post date:** [March 24, 2017, 12:38pm UTC](https://discourse.slimframework.com/t/route-and-middleware-strategies/1291/4 "2017-03-24T12:38:49Z")

</div>

> [@LosLobos](#):
>
> I’m adding these changes directly to Slim but this line suggests that I can use the Container to override the current InvocationStrategyInterface, is this correct ?

Yes!

> [@LosLobos](#):
>
> Can I just write my own InvocationStrategy that implements InvocationStrategyInterface and on the app initialization insert on Container my own Handler ?

Yes!

> [@LosLobos](#):
>
> Also this doesn’t change the way that Middlewares are executed right ? If I would like to make Slim execute my Middleware’s invoke method, how I would do that ?

Yes, won’t change.  
There is no easy way to do it but if you want you will need to implement your own [MiddlewareAwareTrait](https://github.com/slimphp/Slim/blob/3.x/Slim/MiddlewareAwareTrait) (Probably change [this](https://github.com/slimphp/Slim/blob/3.x/Slim/MiddlewareAwareTrait.php#L73) line)  
Then extends [App](https://github.com/slimphp/Slim/blob/3.x/Slim/App.php) and [Route](https://github.com/slimphp/Slim/blob/3.x/Slim/Route.php) to use your MiddleWareAwareTrait  
As you had to change `Route` you will have to extends [Router](https://github.com/slimphp/Slim/blob/3.x/Slim/Router.php) and reimplement [createRoute()](https://github.com/slimphp/Slim/blob/3.x/Slim/Router.php#L206) to use your own Route Then inject your new `Router` on Dependency Container(Like the Invocation Strategy)

You can see the Services on Container [here](https://www.slimframework.com/docs/concepts/di.html#required-services)

---

<div class="post-metadata">

**Author:** ![LosLobos](https://yyz2.discourse-cdn.com/flex030/user_avatar/discourse.slimframework.com/loslobos/32/142_2.png) [@LosLobos](https://discourse.slimframework.com/u/LosLobos)\
**Post date:** [March 24, 2017, 5:35pm UTC](https://discourse.slimframework.com/t/route-and-middleware-strategies/1291/5 "2017-03-24T17:35:20Z")

</div>

Thanks for the help !

Now I can handle myself here. I was not aware of the Services on Container ( I checked the docs a long time ago, maybe it wasn’t there ).

I’ll implement my own MiddlewareAwareTrait to make it work. Hope on Slim 4 there’ll be an easier way to do that. ( Altought is not that hard doing it ).

The help was very much appreciated.

Thanks,  
LosLobos.
