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

when phalcon plungin or complement init

Phalcon\Mvc\User\Plugin,

Phalcon\Mvc\User\Component,

only i know is class extends Plugin can access $di service, like $this->di->request,

but i don't find when these two are init or __contstruct from phalcon source code,anyone has idea?



4.8k
Accepted
answer

See:
Phalcon\Mvc\User\Plugin: https://github.com/phalcon/cphalcon/blob/master/phalcon/mvc/user/plugin.zep
Phalcon\Mvc\User\Component: https://github.com/phalcon/cphalcon/blob/master/phalcon/mvc/user/component.zep
Phalcon\Mvc\User\Module: https://github.com/phalcon/cphalcon/blob/master/phalcon/mvc/user/module.zep

They're empty classes which extend \Phalcon\Di\Injectable and add no extra functionality.
Future functionality may become avilable to these, but otherwise they're there for semantic reasons as explained here:
https://forum.phalcon.io/discussion/1400/difference-between-phalcon-mvc-user-component-plugin-and-module-

Injectable can be found here: https://github.com/phalcon/cphalcon/blob/master/phalcon/di/injectable.zep
It relies on Phalcon\Di\getDefault(); in conjunction with PHP's __get magic method.

When you use $this->di it actually goes through __get followed by the logic here: https://github.com/phalcon/cphalcon/blob/4b37bdfaf277b4493532e5ead1dfc9449fe3ed17/phalcon/di/injectable.zep#L140-L143

Only afterwards, it returns the stored result of \Phalcon\Di::getDefault();

So the only magic going on is \Phalcon\Di::getDefault(); and storing the result within the class behind the scenes to save from multiple calls to \Phalcon\Di::getDefault(); which would all return the same thing anyways.

Note that \Phalcon\Di::getDefault(); relies on the static value of _default and thus getDefault() merely returns its value. There's also a method called setDefault which can change the instance getDefault() returns. You should never need to call this manually, unless you're doing some sort of manual bootstrapping to avoid launching the factory default shown here:
https://github.com/phalcon/cphalcon/blob/master/phalcon/di/factorydefault.zep

Feel free to use __construct with any of the above mentioned three.
There's no initilization taking place, only Phalcon\Di\getDefault(); in conjunction with PHP's __get magic method as previously explained and shown here:
https://github.com/phalcon/cphalcon/blob/master/phalcon/di/injectable.zep



530

when i run phalcon web app. new \Phalcon\Di\FactoryDefault, which extends \Phalon\Di.

then FactoryDefault __construct will call patent __construct, the DI default will be set.

when i call class extends plugin or componment. i can access Di default

thx very much. and sry for latelly to see your reply