DEV Community

Joshua Johnson for UA1 Labs

Posted on • Originally published at ua1.us on

2

FireDI – Advanced Use Cases

FireDI can do a lot more than just resolve your dependencies for you. This tutorial, we are going to cover other scenarios where FireDI can become helpful.

For Mocking In Test Cases

When working on testing your code, you will find that from time to time, you will need to mock a dependency for the class you are testing.

<?php
class TheClassImTesting {
    public function __construct(MyDependentClass $myDependentClass) {}
}

Now to mock MyDependentClass!

<?php
$fireDi = new \UA1Labs\Fire\Di();
$myDependentClassMock = Mock::get('MyDependentClass');
$fireDi->set('MyDependentClass', $myDependentClassMock);

$theClassImTesting = $fireDi->get('TheClassImTesting');

For Injecting New Objects Every Time

By default, FireDI will cache all objects (including object dependencies) within the container object cache. This is so the next time you need the object, it is already ready for you and is just simply returns. From time to time, however, you may need for a specific object to return a new instance every time it is needed.

<?php
// to prevent an object from caching, you may pass a factory into the Di::set() method.

$fireDi = new \UA1Labs\Fire\Di();
$fireDi->set('MyNewObjectEveryTime', function() {
    new MyNewObjectEveryTime();
});

For Interface Dependencies

In many cases, you might have a class that has a constructor dependency on an interface.

<?php
inteface MyInterface {}

class MyClass implements MyInterface {}

class InterfaceDependentClass 
{
    public function __construct(MyInterface $MyInterface) {}
}

In the example above, you will notice that InterfaceDependentClass depends on an object that implements MyInterface. If you want to resolve this, you would need to new MyClass() and pass the resulting instance object into the InterfaceDependentClass constructor. Or you can simply have FireDI do that for you!

<?php
$fireDi = new \UA1Labs\Fire\Di();
$myClass = $fireDi->get('MyClass');
$fireDi->set('MyInterface', $myClass);

$interfaceDependentClass = $fireDi->get('InterfaceDependentClass');

The post FireDI – Advanced Use Cases appeared first on UA1 Labs.

Top comments (0)

👋 Kindness is contagious

Engage with a wealth of insights in this thoughtful article, valued within the supportive DEV Community. Coders of every background are welcome to join in and add to our collective wisdom.

A sincere "thank you" often brightens someone’s day. Share your gratitude in the comments below!

On DEV, the act of sharing knowledge eases our journey and fortifies our community ties. Found value in this? A quick thank you to the author can make a significant impact.

Okay