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

DI and Phalcon\MVC\Model

$loader = new Phalcon\Loader();

    $config = new \Phalcon\Config\Adapter\Ini('../Application/My/Config/config.ini');

    $di = new \Phalcon\DI\FactoryDefault();
    $di->set('db', function() use ($config) {
        return new \Phalcon\Db\Adapter\Pdo\Mysql($config->Database->toArray());
    }, true);

    $myModel = \My\Model\Object\MyModel::findFirst();

Just starting out with Phalcon. In the above code I can succesfully get the first of my model objects from the database set within the DI container. But how does the static model call even know of the DI container I have instantiated? This seems to go against the very concept of dependency injection.

I have the same question.


I think, you can find answer in /phalcon/build/32bit/phalcon.c ++17903 Model use builder, and call builder __construct method ++17932, which is determined DI.

The same situation occurs with controllers. I can instantiate a controller and it already has the DI container that I never set on it. Perhaps this is true for all classes that implement the Phalcon\DI\InjectionAwareInterface? Is this really dependency injection? The DI container is more like a global and is so pervasive through the layers that I don't see the difference between the way this has been implemented opposed to just having a bunch of globally available service/session/db/whatever objects. If a programmer is not careful or inexperienced isn't there huge scope for abuse of this DI container? ie Any Phalcon\DI\InjectionAwareInterface object can implement code that can effect the entire application. My understanding of DI/IOC is that it should be used only within the aggregate root of the application. I like Phalcon but I'm a little disappointed with this aspect.

To my mind phalcon uses last definded DI as default. It's conviniet in a small app, but you can always use setDI method if you need