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

Multiple model directories

I am new to Phalcon so please bare with me. I have created a new folder named 'forms', to store my custom form models. I cannot seem to use these in my controller, unless the class is located directly within the directory of the modelsDir configuration, which is set to the default value: DIR . '/../../app/models/'. app/models/forms/CustomForm does not work either since the model is within a subfolder of the configured directory value. Which brings me to my question: Can the 'modelsDir' key in the configuration hold multiple values/directories? It would be nice to seperate my different kind of models according to their purpose.

Thanks in advance.



899
Accepted
answer
edited Jun '14

You can setup autoloading for namespaces and set namespace paths in your individual models. Namespaces allow you to structure your models/controllers/plugins/... while keeping an minimal overhead.

index.php

$loader = new \Phalcon\Loader();
$loader->registerNamespaces(
    array(
       'App\Controllers' => __DIR__.'/../../app/controllers',
       'App\Models' => __DIR__.'/../../app/models'
    )
)->register();

[...]

$di->set('router', function() {
    $router = new \Phalcon\Mvc\Router();
    $router->setDefaultNamespace('App\Controllers');
    return $router;
});

forms/CustomForm.php

namespace App\Models\Forms;

class CustomForm
{
}


12.1k
edited Jun '14

Hi Wenzel,

Thanks for the quick reply. I have added the following to index.php of the Public folder:

    $loader = new \Phalcon\Loader();
    $loader->registerNamespaces(
        array(
            'MyProject\Forms' => __DIR__.'/../../app/forms'
        )
    )->register();

Inside of the controller:

    $form = new \MyProject\Forms\CustomForm();

However, the controller is still unable to load the specified form class. Any idea what i might be missing/doing wrong?

edited May '14

You have to ensure that the file CustomForm.php contains the namespace declaration namespace MyProject\Forms\CustomForm; at the beginning of the file.



12.1k

That is already the case, the declaration in the controller should be correct since it was generated using autocompletion. Any ideas?

Depending on your phalcon version you need to rename your forms directory to Forms. Since it worked before your file permissions should be right. If you just added the $loader part to your bootstrap file, remove the old parts containing the directory references, since there are some bugs if different types are registered. You have to decide whether to use namespaces or not.



12.1k

I got it working, i removed the loader code from my bootstrap file and added it into the app/config/loader.php file.

Thanks for the help!