PHP API controller class object/instance creation
07:13 04 Jun 2026

First of all, sorry for the noob question, but I feel I am missing something. I have the following PHP code. I don't understand how is the $controller variable created and then recreated as a new $controller. Does it, somehow, go inside the Controller.php file and look for a method called like the url controller parameter?

add('/public/bookings/home', array(
    'controller' => 'Bookings',
    'action' => 'index'
));
$router->add('/public/bookings/get', array(
    'controller' => 'Bookings',
    'action' => 'getBookings'
));

$router->add('/public/bookings/get/{id}', array(
    'controller' => 'Bookings',
    'action' => 'getBookingId'
));

$router->add('/public/bookings/new', array(
    'controller' => 'Bookings',
    'action' => 'createBooking'
));

$router->add('/public/bookings/update/{id}', array(
    'controller' => 'Bookings',
    'action' => 'updateBooking'
));

$router->add('/public/bookings/delete/{id}', array(
    'controller' => 'Bookings',
    'action' => 'deleteBooking'
));

$url_path = explode('/', $request_uri);
$url_public = $url_path[1]
$url_controller = $url_path[2]
$url_action = $url_path[3]
$url_params = $url_path[4]

$urlArray = array(
    'HTTP' => $_SERVER['REQUEST_METHOD'],
    'path' => $request_uri,
    'controller' => $url_controller,
    'action' => $url_action,
    'params' => $url_params
);

if(empty($url_controller)){
    $urlArray['controller'] = 'Booking';
    $urlArray['action'] = 'index';
}

if(empty($url_action)){
    $urlArray['action'] = 'index';
}

if ($router->matchRoute($urlArray)) {
    $method = $urlArray['HTTP'];
    $params = [];

    if ($method === 'GET') {
        $params[] = intval($urlArray['params']) ?? null;
    } elseif ($method === 'POST') {
        $json = file_get_contents('php://input');
        $params[] = json_decode($json, true);
    } elseif ($method === 'PUT') {
        $id = intval($urlArray['params']) ?? null;
        $json = file_get_contents('php://input');
        $params[] = $id;
        $params[] = json_decode($json, true);
    } elseif ($method === 'DELETE') {
        $params[] = intval($urlArray['params']) ?? null;
    }
    $controller = $router->getParams()['controller'];
    $action = $router->getParams()['action'];
    $controller = new $controller();

    if (method_exists($controller, $action)) {
        $resp = call_user_func_array([$controller, $action], $params);
    } else {
        echo "Method not found";
    }
} else {
    http_response_code(404);
    header('Content-Type: application/json');
    echo json_encode([
        "error" => "Not Found",
        "message" => "Requested route does not exist",
        "path" => $url
    ]);
    exit;
}
php controller