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

Use PHQL from an external class (out of Controllers)

Hello folk! I'm trying to run a PHQL from an external class, but I got the following error:

A dependency injection object is required to access ORM services

This is my code:

$modelsManager = new Manager();
        $res = $modelsManager->executeQuery(
          $phql,
          [
            'name' => $name,
            'age'     => $age,
            'color'   => $color
          ]
        );

At the top, I have included this:

use Phalcon\Di;
use Phalcon\Mvc\Model\Manager;

What is wrong? Must I use Micro? I don't know how to make it work.

Related thread: https://forum.phalcon.io/discussion/877/error-message-when-using-integer-filter-in-getquery-function-of-

edited Dec '17

And where you have this code? You need to access manager for di(modelsManager service) or set Di for this new manager.



13.9k

Thanks for answering!

This external class is placed in /app/somewhere/External.php.

Yeah, that's I want: access to manager, but I'm a bit new at MVC, so I don't get it quickly. Sorry.

Could you tell me how can I access it?

You need to access DI from your appliaction obviously. But framework should acces it itself. If it doesn't then it means that you don't have DI in your app at all so im not sure what are you doing. Just make this class extends Injectable and just do $this->modelsManager



13.9k

Hmm, now put extends Injectable in my Class and I got this error:

Fatal error: Class 'Injectable' not found

This file is outside /app/controller/ is that the reason? is isolated.



145.0k
Accepted
answer
edited Dec '17

You need to add use keyword with proper namespace obviously. What IDE you use? It should inform you about it.

I think it's obvious i meant Phalcon\Di\Injectable



13.9k

I use Geany as my editor