We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

What is the right way to add namespace for your application?

I am working on a micro application and want to use namespace BII for my api

  1. so i have "namespace BII;" added to almost all my code files
  2. registered by controllers directory in config.php -> 'controllersDir' => APP_PATH . '/controllers/',
  3. loader.php also registers my directory as $config->application->controllersDir

But still i am not able to initialize my controller class - i get this error

Fatal error: Class 'BII\ProjectsController' not found in C:\Users\user\Sites\bii\app.php on line 10 This is how my Projectscontroller code looks

namespace BII; use \Phalcon\Mvc\Controller;

class ProjectsController extends Controller {

public function indexAction() {

    $message = array('message' => 'Hello, listing all projects');
    echo json_encode($message);
}

}

what am i doing wrong?

Ok, now i removed the namespace and it works ProjectsController is hooked up -,



93.7k
Accepted
answer

Here is sample code from multimodule application of mine:

class Module
{ 
    public function registerAutoloaders($di)
    {    
        $loader = new \Phalcon\Loader();
        $namespaces = array(
            'Backend\Controllers' => __DIR__ . '/controllers/', 
            'Backend\Forms' => __DIR__ . '/forms/',
            'Models' => __DIR__ . '/../../common/models/', 
            'Helpers' => __DIR__ . '/../../common/helpers/', 
        ); 
        $loader->registerNamespaces($namespaces);
        $loader->register(); 
    }

Are you sure BOTH file name and calss name are called ProjectsController ?