The Slim Framework support forum has moved to http://discourse.slimframework.com. This Tender forum is no longer maintained or monitored.

How to get pathFor in middleware class?

ssh.eduardo's Avatar

ssh.eduardo

02 Jan, 2016 03:22 PM

Hi,
I have a middleware class

<?php
namespace App\Middleware;

use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use RKA\Session;

class Validations
{
    private $route;
    private $strict;

    public function __construct($route = '/', $strict=false)
    {
        $this->route = $route;
        $this->strict = $strict;
    }
    public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next)
    {
        $session = new Session();
        //Example
        if(true) { 
            $url = $this->app->router->pathFor('login');
            return $response->withRedirect($url);
        }
        $response = $next($request, $response);
        return $response;
    }
}

The error:

 Notice: Undefined property: App\Middleware\Validations::$app in /xxx/src/middleware/Validations.php
How to get pathFor correctly (where inject $app)?
Sorry, for my bad english.
  1. 1 Posted by ssh.eduardo on 05 Jan, 2016 09:50 PM

    ssh.eduardo's Avatar

    Anyone can help me?

  2. 2 Posted by kosikredek on 12 Jan, 2016 01:51 PM

    kosikredek's Avatar

    $app->add(new ExampleMiddleware($app->getContainer()->get('router')));

    class ExampleMiddleware
    {
        protected $router;
    
        public function __construct($router)
        {
            $this->router = $router;
        }
    
        public function __invoke($request, $response, $next)
        {
            $path = $this->router->pathFor('user-password-reset', ['id' => 13]);
    
            $response = $next($request, $response);
    
            return $response;
        }
    }
    
  3. 3 Posted by ssh.eduardo on 12 Jan, 2016 09:35 PM

    ssh.eduardo's Avatar

    As it never occurred to me before?

    Thanks

Reply to this discussion

Internal reply

Formatting help / Preview (switch to plain text) No formatting (switch to Markdown)

Attaching KB article:

»

Attached Files

You can attach files up to 10MB

If you don't have an account yet, we need to confirm you're human and not a machine trying to post spam.

Keyboard shortcuts

Generic

? Show this help
ESC Blurs the current field

Comment Form

r Focus the comment reply box
^ + ↩ Submit the comment

You can use Command ⌘ instead of Control ^ on Mac