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.

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!



33.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!