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

Load namespaces from files

Hey!

I have a question regarding namespaces, from all the documentation I can find, you have to expressively define every single namespace and its dir. I want to define the root namespace and then have directories correspond to namespaces, like this:

index.php:

<?php

$loader = new \Phalcon\Loader();
$loader->registerNamespaces(
    array(
        "Application" => "/"
    )
);
$loader->register();

Now, if I create for example the file app/utils/validators/EmailValidator.php: ...

<?php

namespace Application\Utils\Validators;

class EmailValidator {}

... I want to be able to access this class without having to manually add Application\Utils and Application\Utils\Validators in the loader. Do I really have to register everything manually?

Regards, dimhoLt



51.2k

It's a PSR rule that Phalcon should apply. In namespace, you should have the directories with the first letter in uppercase. So if you register 'Application' to '/' then your dir structure should be:

    /
        Utils
            Validators
                EmailValidator.php


22.6k

Actually, this appears to work... I must have done something wrong earlier. I'll update this thread if I find my mistake.