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)