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

Setting up DI for testing - TestHelper.php example

I'm setting up my testing environment and in the docs there is an example for a PHPunit helper file.

In this helper file at the end there is

$di = new FactoryDefault();
DI::reset();

// Add any needed services to the DI here

DI::setDefault($di);

As far as I understand when a DI is created it registers itselft as the default one, so calling DI::getDefault() will always return the last DI created. So why in the example we have DI:reset() and then a DI::setDefault($di) if we didn't create another DI?

It seems kinda redundant. It would only make sense if Di::setDefault() creates a copy of the container instead of having a reference to it. Am I missing something here?



32.2k
edited Oct '15

Not really. I'd like to understand what would be the potential effects of not calling DI:reset() in that context.



47.7k

Then why don't you try it?



32.2k

I currently ommited DI:reset() without any issues. I'm trying to figure out what's the idea behind it. I imagine some components will use the defaut DI if you don't pass a DI as argument, but if you don't have a default one what happens? Will they fail? And in the case you pass a DI as an argument wouldn't it take precedence over the default one anyway?

I'm looking for places in the source code where having a default DI setup would make a difference, and so far I couldn't find any conclusive information.



47.7k
edited Oct '15

My assumption is that DI:reset() is used in the teardown.

Say you want the reference to a db service the same but you'd like to test different adapters? Doesn't the DI need to be reset?

Looking at the example code I can see :

    $di = new FactoryDefault();

This gives you the full stack of services.

So maybe this is quoted...

    DI::reset();

.. to point how you can switch back to a default or bespoke one.

I'm not sure if I am grasping the thrust of what you are saying.



32.2k

My point is that in the example they are creating a new DI (that becomes the new default), then reseting the default, adding more services to that container and then setting that container as the default again! What effect would having no default DI container have on the new services being created and attached to that same container? That's what is bogging my mind!



47.7k
edited Oct '15

I'm not sure you are supposed to read it in sequence like that. Maybe its not such a great example.

I think its just there as an illustrative example not a literal one.