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

Micro framework using standard PHP class models

Hi Forum,

I am trying to learn Phalcon and write a micro application that references a Postgresql database. The database makes extensive use of database views and 'stored procedures' for the 'Select' and 'Insert / Update' processes respectively.

As the process is asymetric the database does not allow direct access to the tables, I assume I can't use or modify the ORM for this process.

I am writing standard PHP classes but can not work out how I reference the di container in the custom 'Model' class?

Can anyone provide guidance on this?

edited Nov '19

Models don't have direct access to the DI like controllers or components do. You can use \PhalconDI::getDefault() anywhere though, and it will return the DI.

Here's a method I always put in my base Model class (that extends \Phalcon\Mvc\Model and is extended by all custom models:

/**
     * @param string $thing_in_di [OPTIONAL]  If provided, causes the method to return that item in the DI, rather than the DI itself
     * @param array $parameters_for_thing [OPTIONAL] If provided, passes the parameters on to the closure method for creating the thing
     * @return \Phalcon\Di|mixed    Either the DI container, or a particular service
     */
    protected function di($thing_in_di=NULL,$parameters_for_thing=NULL){
        if($thing_in_di == NULL){
            return \Phalcon\DI::getDefault();
        }
        else{
            return \Phalcon\DI::getDefault()->get($thing_in_di,$parameters_for_thing);
        }
    }

Use it like:

$SomeModel = SomeModel::findFirst();
$Service = $SomeModel->di('name-of-service');