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

How to store anonymous functions as "services" in Phalcon\DI (version 1.3.0) ?

After updating Phalcon from 1.2.6 to 1.3.0, it keeps saying:

Usage of Phalcon\DI to store non-objects is deprecated, please use Phalcon\Registry

The thing is, we didn't use the Dependency Injector only as Iversion of Control container. We stored some helper functions, that use the $di, as "services" in it too.

As an example (very dumb one):

$di->set('add', function($num1, $num2) use ($di) {
    return $di->get('calculator')->add($num1, $num2);
});

Phalcon suggests to use Registry for it as it does not return an object. But in this context it doesn't work.

I know the best approach is to extract these helper (anonymous) functions to a class and then inject it in the container. But what would be the best approach to get this woking by now (without refactoring)?



125.8k
Accepted
answer

Well straight off, you're going to need to re-code some things - I don't think there's a quick and easy solution other than ignoring the error. No matter what you do you're going to have to revisit every spot that references $di->get("add")(1,2) (to follow your example). Since you're going to be digging through your code anyway, you might as well take the effort to "bring it up to spec" and use the registry

Sure thing!

For the time being I just replaced this:

$di->set('add', function($num1, $num2) use ($di) {
    return $di->get('calculator')->add($num1, $num2);
});

By:

$di->get("registry")->add = function(\Phalcon\DiInterface $di, $num1, $num2) {
    return $di->get('calculator')->add($num1, $num2);
});

But it isn't a good design yet. I'm gonna do some refactoring when the time comes. It's worthy of extracting all these functions to a Helper class.

Thank you very much @quasipickle