Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

autoloader can't load classes in multi module project

I'm developing a multi module project, and I met some trouble, please help.

The enviroment is win7x64, wamp-2.5-x64, phalcon-2.0.2-x64

I copied the sample code from the official document, in index.php, simply add a router to explain the url, in module.php, I add autoloader to load my controllers and models, but they are not found

public function registerAutoloaders(\Phalcon\DiInterface $dependencyInjector = NULL) {

    $loader = new \Phalcon\Loader();

    $loader->registerNamespaces(array(
        'Multiple\Entrance\Controllers' => __DIR__ . '/controllers/',
        'Multiple\Entrance\Models' => __DIR__ . '/models/',
    ))->registerDirs(array(
        __DIR__ . '/controllers/',
        __DIR__ . '/models/',
    ))->register();

    var_dump($loader->getNamespaces());
    var_dump($loader->getClasses());
}

it's very strange var_dump($loader->getNamespaces()) can output the directories and the namespaces,

but var_dump($loader->getClasses()); outputs null

I can't understand it. Also in the following codes, the classes in controllers and models can't be found.



3.0k
Accepted
answer

the classes in controllers and models can't be found. - coz it's differance namespce your defaut is ''

This is my way.

  • I use phalcon dev tools to generate model in own directory, Database cms in directory ../app/models/cms
  • In model files add namespace Cms; and
    public function initialize()
    {
        // By default "db" is choose for phalcon, you may specify other connection in your
        $this->setConnectionService("dbCms");
    }
  • index.php add
    $config = new Phalcon\Config\Adapter\Ini(__DIR__ . "/../app/config/config.ini");

    $di = new Phalcon\DI\FactoryDefault;
    $di->set('dbCms', function () use ($config) {
        return new Phalcon\Db\Adapter\Pdo\Mysql(
            [
                "host" => $config->dbCms->host,
                "username" => $config->dbCms->username,
                "password" => $config->dbCms->password,
                "dbname" => $config->dbCms->dbname,
                "options" => [
                    PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'UTF8'",
                    PDO::ATTR_CASE => PDO::CASE_LOWER,
                    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_OBJ,
                ],
            ]);
    });

    $loader = new Phalcon\Loader;
    $loader->registerNamespaces([
        'Cms' => $config->phalcon->modelsCmsDir,
    ]);

now your code is something like $myModell = new Cms\ExampleModell(); Hope this help.