Good day. For the sake of self-education I decided to write my own framework, I encountered the following problem.

There is such a construction

$route = new Route(); $currentController = $route->getCurrentRoute(); spl_autoload_register(function () use ($currentController) { $controllerFileName = __DIR__ . '/../App/Controllers/' . $currentController['controller'].'Controller' . '.php'; if(file_exists($controllerFileName)) { include $controllerFileName; } }); $controllerName = $currentController['controller'].'Controller'; $controller = new $controllerName; 

I appeal in the browser to the root of the site. The DefaultController should start. However, the answer is an error:

Class 'DefaultController' not found in Core.php (23): Core \ Core-> activeController ()

controller code

  <?php namespace App\Controllers; use \Core\View; use \Core\Controller; /** * Class Default * @package App\Controllers */ class DefaultController extends Controller { public function indexAction() { View::renderTemplate('Home/index.html'); } } 

What am I doing wrong?

  • In $currentController['controller'] what? - vp_arth

3 answers 3

When instantiating an object from a string, the string must contain the full namespace of the class:

  $ctrl = 'Default'; $controllerName= "App\\Controllers\\{$ctrl}Controller"; $controller = new $controllerName; 

    Apparently, the path to the file is not searched correctly for you, check that inside the $controllerFileName variable:

     $controllerFileName = __DIR__ . '/../App/Controllers/' . $currentController['controller'].'Controller' . '.php'; 
    • > /var/www/test/Core/../App/Controllers/DefaultController.php This is the line - Nikita Rassamahin
    • Is the path correct to the file? - Yaroslav Molchan
    • Yes, I checked. file_exists ($ controllerFileName) returns true - Nikita Rassamahin
    • If you write statically include '/var/www/test/Core/../App/Controllers/DefaultController.php'; will the code work? and then check if it doesn't work: include '../App/Controllers/DefaultController.php'; - Yaroslav Molchan

    Good day. Try to make it easier. Define by default the path to your files. And it will be something like:

     spl_autoload_register(function($class) { $path = "Classes"; if(strpos($class, "Controller") > 0) { $path = "Controllers"; } else if (strpos($class,"Model") > 0) { $path = "Models"; } $classFile = "../$path/$class.php"; file_exists($classFile) ? require_once ("../$path/$class.php") : die("Class not found!"); }); 

    Hope to help =)