bramus / router

A lightweight and simple object oriented PHP Router
MIT License
1.08k stars 247 forks source link

No executing middleware #210

Open ghost opened 1 year ago

ghost commented 1 year ago

I tryed to execute like the documentation

$router->before('GET|POST', '/admin/.*', function() { if (!isset($_SESSION['user'])) { header('location: /auth/login'); exit(); } });

but isnt working the request goes direct into private side of application without check if user has access and is loged

drnkwati commented 1 year ago

Hello @gitbucket-crypto It might not work for several reasons: try the following: session_start() session_status()

Check PHP session documentation

https://www.php.net/manual/en/ref.session.php

ghost commented 1 year ago

I discovered the problem, the node '/admin/.*, has setted data in global $_REQUEST like other nodes but the internal handler for requisition never uses that, I made my handler for this problems

` class Handler { public function __construct() {

}

const CALLABLE  = 1;
const INVOKE = 2;

public function handle($type, $fn, $params = [])
{
    list($controller, $method) = explode('@', $fn);
    switch($type)
    {
        case Handler::CALLABLE :
            $controller = new $controller($params);
            $className = get_class($controller);
            $methodVariable = array($controller,  $method); 

            if(is_callable($methodVariable, true, $callable_name)==true){

                call_user_func($methodVariable, $params); 
                unset($controller);
                unset($params);
            }
            else 
            {
                 $this->handle( Handler::INVOKE,$fn, $params); 
            }
            exit;

        break;
        case Handler::INVOKE :
            $reflectedMethod = new \ReflectionMethod($controller, $method);
            if (class_exists($controller) & ($reflectedMethod->isStatic()==false) )
            {
                $controller = new $controller($params);
                $reflectionClass = new \ReflectionClass(get_class($controller));
                $reflectionMethod = $reflectionClass->getMethod(strval($method));
                $reflectionMethod->setAccessible(true); 
                $reflectionMethod->invoke(new $controller($params)); 
                unset($controller);
                unset($params);
                unset($reflectedMethod);
                unset($reflectionMethod);
            }
            else
            {
                 $this->handle( Handler::CALLABLE,$fn, $params); 
            }
        break;
    }
}

}`