Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

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.0k
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.phalconphp.com/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



293

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