how to use the $_GET superglobal on the php mvc application

Viewed 48

I am working on a full blown php mvc application everything about the structure is fine. Except one thing. Take a look at the code first:

<?php

require_once __DIR__.'/vendor/autoload.php';
use app\core\route;
use app\controllers\apicontroller;
route::get('/api', [apicontroller::class, 'api']);

Now this is the file that i created for all the incoming requests that passes through the application works and pass through here

Now i want a way i would be able to use the $_GET superglobal as a parameter on the route.

Take a look at where i created the route class as a static function

namespace app\core;
class route{
    // get request
   public static function get(string $path, callable $method){
    if ($_SERVER['REQUEST_URI'] == $path) {

        if ($_SERVER['REQUEST_METHOD'] != 'GET') {
            exit('This path accepts only GET requests');
        }
        return $method();
    }
   }
   public static function post(string $path,callable $method){
    if ($_SERVER['REQUEST_URI'] == $path) {

        if ($_SERVER['REQUEST_METHOD'] != 'POST') {
            exit('This path accepts only GET requests');
        }
        return $method();
    }
   }
   }

Now all i need is way i can use the route this way: http:://localhost/api?u=123

To be able to get the parameter from my controller because its not working or let me say is not outputting it

Here is the controller for the apicontroller class:

namespace app\controllers;
// use app\core\database;
use app\model\user;
class apicontroller{

public static function api(){
       if(isset($_GET['u'])){
echo $_GET['u'];
// not outputting
}
}
}
1 Answers

Maybe you should handle the first parameter of yhe get method of your route::class so that it is variable in appropriate cases In your route::class:

public static function handleGetData($path){
$request = $_SERVER['REQUEST_URI'];
$getRequest = explode('?' ,$request, 2);
$getData = null;

if (isset($get_request[1])) 
    $getData = '?' . $getRequest[1];

if (!isset($getRequest[1])) 
    $getData = '';

return $path .$getData;

}

In your index.php :

<?php
    require_once __DIR__.'/vendor/autoload.php';
    use app\core\route;
    use app\controllers\apicontroller;

    route::get( route::handleGetData('/api'), [apicontroller::class, 'api']);

Now normally your get data will comme and you will be able to handle it in your controller. I think you need to define a 404 method for undefined cases in you route::class

Related