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.

Namespace Models not working

Hi,

My models aren't found, and i don't know why.

My loader :

    use Phalcon\Loader;

    $loader = new Loader();

    $loader->registerDirs(
    [
        'Controllers' => __DIR__ . '/../../app/controllers/',
        'Models' => __DIR__ . '/../../app/models/',
    ]
    )->register();
    DebugBreak("[email protected];d=1,p=0");
    //load modules controllers namespaces
    foreach (glob($config->application->controllersDir . '*', GLOB_ONLYDIR) as $namespace_name) 
    {
    $module_name = basename($namespace_name);

    $registered_modules["Controllers\\".$module_name] = $namespace_name ;
    }

    foreach (glob($config->application->modelsDir . '*', GLOB_ONLYDIR) as $namespace_name) 
    {
    $module_name = basename($namespace_name);

    $registered_modules["Models\\".$module_name] = $namespace_name ;
    }

    $loader->registerNamespaces($registered_modules)->register();

My model :

    namespace Models\Base;       

    use Phalcon\Phalcon\Mvc\Model;

    class Authentication extends Model
    {
        protected $ID_Authentification;
        protected $Login;
        protected $Mot_De_Passe;
        protected $ID_Poste;
        protected $Token;
    }

And my Controller :

    namespace Controllers\Base;

    use Phalcon\Mvc\Controller;

    class LoginController extends Controller
    {
        public function indexAction()
        {

            $ident = $this->request->getPost("ident");
            $pwd = $this->request->getPost("password");

            $auth = new \Models\Base\Authentification();

            $result = $auth->find(
                [
                    "Login = $ident AND Mot_De_Passe = $pwd"
                ]
            );

            $this->view->result;
        }
    }

Where is my error ?



81.0k
Accepted
answer

You're doing a lot more work in your loader than necessary. It's an auto-loader, so if you define the namespaces properly, it will take care of loading each model as necessary - you don't need to explicitly define each model.

You should be able to define your loader like this:

$loader = new Loader();
$loader->registerNamespaces([
    'Controllers' => __DIR__ . '/../../app/controllers/',
    'Models' => __DIR__ . '/../../app/models/',
])->register();

Also, your model is in the \Models\Base namespace, not the \Models namespace. I believe the autoloader will handle sub-namespaces properly, but perhaps not.

Thx for the explications.

It's work fine.