Search code examples
phpauraphp

How to Send a GET variable to a controller using PHP AURA ROUTER and ZEND DIACTOROS


I'm coding my first MVC PHP APP without any framework only common PHP Libraries, nonetheless, I'm having some problems with the process of sending GET Variables to the Controller, without using the superglobal $_GET.

I am using Aurora Router to map the web routing and Zend Diactoros for the HTTP Message Interfaces.

I have several methods using POST Variables that works as expected, using the $request Diactoros Object, but I can't make work the route: app.test/test/thisGetVar to send "thisGetVar" to the controller Method.

Front Controller:

require_once '../vendor/autoload.php';

use Aura\Router\RouterContainer;

$request = Zend\Diactoros\ServerRequestFactory::fromGlobals(
    $_SERVER,
    $_GET,
    $_POST,
    $_COOKIE,
    $_FILES
);

$routerContainer = new RouterContainer();
$map = $routerContainer->getMap();

$map->get('formhLogin', '/login', [
    'controller' => 'App\Controllers\AuthController',
    'action' => 'formLoad'
]);

$map->get('test', '/test/{var}' , [
    'controller' => 'App\Controllers\TestController',
    'action' => 'getVar',
]);

$matcher = $routerContainer->getMatcher();
$route = $matcher->match($request);

if(!$route){
    echo 'Route not Found';
}else{
    $handlerData = $route->handler;
    $controllerName = $handlerData['controller'];
    $actionName = $handlerData['action'];

    $controller = new $controllerName;
    $response = $controller->$actionName($request);
   
    foreach($response->getHeaders()as $name => $values)
    {
        foreach($values as $value) 
        {
            header(sprintf('%s: %s' , $name , $value), false);
        }

    }
        http_response_code($response->getStatusCode());
        echo $response->getBody();        
}

TestController.php:

namespace App\Controllers;

class PruebaController extends BaseController{
    public function getVar($request){
        $id = $request->getAttribute('id');
        echo $id;
        $getData = $request->getParsedBody();
        echo $getData['id'];
        return $this->renderHTML('test.twig');
    }
}

$getData shows the error: "Notice: Undefined index: id in .."

echo $id (sends no output)

Can anybody help me?

My desired output in this example is: 'thisGetVar'


Solution

  • Before passing the request object to controller method you have to transfer route attributes to the request.

    foreach ($route->attributes as $key => $val) {
        $request = $request->withAttribute($key, $val);
    }