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

Invo Database Connection

I am using the Invo example and curious about how to handle DB Connections within models/controllers.

I know the services.php file defines a connection; but how would one execute a direct SQL query from one (PHQL approach is known, I am trying the direct query approach in this case...)

Do I need to explicitly define a connection instance on the model init?



17.5k

You can always use pdo or mysqli to connect if you want to directly query w/ php. You can use this anywhere in your php code.

edited Jul '15

I think my question is changing as I read more into Phalcon. More specifics follow:

Currently using FactoryDefault, not di.

Question part one is, once a db conn is defined in services.php as it is in Invo, does it need to be assigned within the models or is it globally available. Looks like it is an anonymous function, so I think it should be; but then how to call it?

Second; if it does need to be explicitly defined in a model, would it be advisable to create a ModelBase class, define the connection in the init function, and then inherit?



17.5k

Without looking at your services.php file, I can't say for sure. If it is set up like Invo, then yes... You can access it from anywhere. Here is a thread that explains raw queries:

https://forum.phalcon.io/discussion/2417/use-raw-queries-in-phalconphp

Thanks for the response. Trying to work with the examples on that link. Getting some odd results. Ex: Just trying to print out the DI Object to verify the DB ibject exists fails with:

Notice: Undefined variable: di in /Library/WebServer/Documents/Cyclone/app/controllers/IndexController.php on line 41

echo("<pre>"); print_r($di); echo("</pre>"); die;

However: this works and shows the DB object:

echo("<pre>"); print_r($this->di); echo("</pre>"); die;

Yet, this later example fails with an empty result it I try something like: $this->di->getDB();

I must be missing something. But what?!



7.3k
Accepted
answer

So, I hve figured this out:

In my ControllerBase I have the following in my initialize function: $this->di = \Phalcon\DI\FactoryDefault::getDefault();

And in my IndexController I have this to get a single record: $story = $this->di["db"]->fetchOne("CALL test.website_story_get_by_name('Test');");

Zach, thank you!!!



17.5k

Interesting... Calling stored procs. Glad you figured it out!