I started playing with Auraphp for dependency injection, and I wrote a sample application. It is working as expected, however, I am not sure if I use it in the correct way. Can someone let me know if I am doing right, or is there any better way to use Aura?
This is my public/index.php:
use Aura\Di\ContainerBuilder;
use MyPackage\Base\Service;
use MyPackage\Base\Flow;
require_once dirname(__DIR__) . '/vendor/autoload.php';
$builder = new ContainerBuilder();
$di = $builder->newInstance();
$di->set('baseService', new Service);
$di->set('baseFlow', new Flow);
$service = $di->get('baseService');
$flow = $di->get('baseFlow');
$service->showMessage();
$flow->showMessage();
This is src/Service.php (src/Flow.php is similar):
<?php
namespace MyPackage\Base;
class Service
{
public function showMessage()
{
echo "Inside service";
}
}
I mainly want to know if I am benefiting from dependency injection advantages. Besides, using Aura this way is not memory/CPU/time overloading?
Any thoughts would be appreciated.
In this case you are already instantiating the class. But in most cases you can use lazy loading. In that approach you will also benefit from inserting necessary dependencies needed. So your code will become
The example is taken from : http://auraphp.com/packages/3.x/Di/services.html .
Assume your Flow class have some dependencies, you can either do by constructor injection or setter injection.
Now you can define like
You can see more examples in the documentation. DI sometimes feels magic, but if you understand it correctly it will help you debug things quickly.