Php altorouter namespaces problem class not found

53 Views Asked by At

I'm encountering a problem using altorouter for PHP. I don't understand why my classes won't be detected while my namespaces seem to be ok.

Here is my code :

/composer.json

{
    "require": {
        "altorouter/altorouter": "^2.0.1"
    },
    "autoload": {
        "psr-4": {
            "Controllers\\": "/controllers"
        }
    }
}

/router.php

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

use AltoRouter as Router;
use Controllers\MentionsLegalesController as MentionsLegalesController;

// Initialisation du routeur
$router = new Router();

// Définition des routes
$router->map('GET', '/refonte_site/mentions-legales', function () {
    $controller = new MentionsLegalesController();
    $controller->index();
}, 'mentions-legales');

// Match de la route actuelle
$match = $router->match();

// Si la route est trouvée, on appelle la méthode de la classe associée
if ($match && is_callable($match['target'])) {
    call_user_func($match['target']);
} else {
    // Si aucune route n'est trouvée, renvoie une erreur 404
    header("HTTP/1.0 404 Not Found");
    echo '404 Not Found';
    echo 'Chemin de la requête : ' . $_SERVER['REQUEST_URI'];
    var_dump($match);
}

/controllers/MentionsLegalesController.php

<?php 

namespace Controllers;

class MentionsLegalesController {
    public function index() {
        // Logique pour la page "Mentions légales"
        include __DIR__ . '/../views/mentions-legales.php';
    }
}

Error i'm getting : Fatal error: Uncaught Error: Class "Controllers\MentionsLegalesController" not found in C:\wamp64\www\refonte_site\router.php on line 17 Error: Class "Controllers\MentionsLegalesController" not found in C:\wamp64\www\refonte_site\router.php on line 17

I already tried composer dump-autoload but it did nothing, i'm on this issue for hours :( It works when I require the file where the corresponding class is, but if I understand namespaces and autoloaders well, you normally don't have to require these right ?

UPDATE

I had to change, in composer.json, "/controllers" to "controllers" because autoloader of altorouter seems to not consider absolute path... Problem fixed

0

There are 0 best solutions below