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

PHQL: default namespace

Elo bird lovers,

I'm looking for a feature by which you can set a default namespace for PHQL. The closet thing I found is here, by which every model would have to be setup manually.

1 So when using models residing in SomeApp\Models\..., I could write it like so:

$modelsManager->setDefaultNamespace("SomeApp\Models");
$queryString = "SELECT * FROM Robots JOIN RobotEvents WHERE RobotEvents.type=:eventType:";
$modelsManager->executeQuery($queryString, ['eventType'=>$type]);

2 I imagine accessing models in other namespaces could work with absolute paths:

$queryString = "SELECT * FROM \OtherApp\Models\Robots JOIN RobotEvents WHERE RobotEvents.type=:eventType:";

3 Additional awesomeness would be if you could still use aliases:

$queryString = "SELECT * FROM \OtherApp\Models\Robots JOIN RobotEvents re WHERE re.type=:eventType:";

Do features like these exists? Cheers!



34.6k
Accepted
answer

There is no default namespace but you can use namespace aliases:

use Phalcon\Mvc\Model\Manager as ModelsManager;

// ...

$di->set(
    'modelsManager', 
    function () {
        $modelsManager = new ModelsManager();
        $modelsManager->registerNamespaceAlias(
            'm',
             'Store\Backend\Models\Robots'
         );
        return $modelsManager;
    }
);

And in the queries:

// After
$data = $this->modelsManager->executeQuery("
    SELECT r.*, rp.*
    FROM m:Robots AS r
    JOIN m:RobotsParts AS rp
");

Neat, thank you!