Problem with namespace paths in PHP

Username (e.g. epiz_XXX) or Website URL

epiz_29214392

Error Message

My error/debugging system raises ‘Controller class App\Controllers\Home not found’ from router.php

Other Information

public function dispatch($url)
{
    $url = $this->removeQueryStringVariables($url);

    if ($this->match($url)) {
        $controller = $this->params['controller'];
        $controller = $this->convertToStudlyCaps($controller);
        $controller = $this->getNamespace() . $controller;
        
        
        if (class_exists($controller)) {
            $controller_object = new $controller($this->params);

            $action = $this->params['action'];
            $action = $this->convertToCamelCase($action);

            if (preg_match('/action$/i', $action) == 0) {
                $controller_object->$action();

            } else {
                throw new \Exception("Method $action in controller $controller cannot be called directly - remove the Action suffix to call this method");
            }
        } else {
            throw new \Exception("Controller class $controller not found");
        }
    } else {
        throw new \Exception('No route matched.', 404);
    }
}

My site is based on https://github.com/daveh/php-mvc and works perfectly fine when I’m using it with MAMP locally however it doesn’t find the classes defined within App\Controllers from router.php located in Core. Anyone got any ideas?

To clarify after further investigation, I believe that this is an issue with composer autoload not working even though it has been required in my index.php. Any ideas?

    {
    "require": {
        "twig/twig": "~3.0"
    },
    "autoload": {
        "psr-4": {
            "Core\\": "Core/",
            "App\\": "App/"
        }
    }
}

I think the issue is with the class naming. If you want to use a class without importing it with use, you have to prepend it with a slash. So new \App\Controllers\Home() works, but new App\Controllers\Home() does not. Looking at the error message, I don’t think the value of $controller starts with a \.

I have solved the problem by requiring the controllers manually instead of through composer’s autoload

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.