I’m getting a “class not found” error trying to make a Router work:
GET / - Uncaught Error: Class "AppRouter" not found in /home/zumb/Documents/HHsite/ALPHA_VERSION/public/index.php:4
Stack trace:
#0 {main}
thrown in /home/zumb/Documents/HHsite/ALPHA_VERSION/public/index.php on line 4
I don’t understand why it can’t find my class.
My folders :
public
-index.php
src
-Router.php
vendor
-altorouter
-composer
-autoload.php
views
tableau.php
composer.json
composer.lock
index.php :
<?php
require '../vendor/autoload.php';
$router = new AppRouter(dirname(__DIR__) . DIRECTORY_SEPARATOR . 'views');
$router
->get('', 'tableau', '')
->get('/blog/category', 'category/show', 'category')
->run();
Router.php :
<?php
namespace App;
class Router {
/**
* @var string
*/
private $viewPath;
/**
* @var AltoRouter
*/
private $router;
public function __construct(string $viewPath)
{
$this->viewPath = $viewPath;
$this->router = new AltoRouter();
}
public function get(string $url, string $view, ?string $name = null)
{
$this->router->map('GET', $url, $view, $name);
return $this;
}
public function run()
{
print "hey";
$match = $this->router->match();
$view = $match['target'];
ob_start();
require $this->viewPath . DIRECTORY_SEPARATOR . $view . '.php';
$content = ob_get_clean();
require $this->viewPath . DIRECTORY_SEPARATOR . 'layouts/default.php';
return $this;
}
}
composer.json :
{
"autoload": {
"psr-4": {
"App\": "src/"
}
},
"require": {
"altorouter/altorouter": "^2.0"
}
}
autoload.php :
<?php
// autoload.php @generated by Composer
if (PHP_VERSION_ID < 50600) {
if (!headers_sent()) {
header('HTTP/1.1 500 Internal Server Error');
}
$err = 'Composer 2.3.0 dropped support for autoloading on PHP <5.6 and you are running '.PHP_VERSION.', please upgrade PHP or use Composer 2.2 LTS via "composer self-update --2.2". Aborting.'.PHP_EOL;
if (!ini_get('display_errors')) {
if (PHP_SAPI === 'cli' || PHP_SAPI === 'phpdbg') {
fwrite(STDERR, $err);
} elseif (!headers_sent()) {
echo $err;
}
}
trigger_error(
$err,
E_USER_ERROR
);
}
require_once __DIR__ . '/composer/autoload_real.php';
return ComposerAutoloaderInitcdc540639fbf1cb4b940a9197d9773c3::getLoader();
I tried “composer dump-autoload”.
It works if I just “require” and “use”.
How can I fix this?
New contributor
zumb is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.