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.
$di->set('baseService', new Service);
$di->set('baseFlow', new Flow);
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
$di->set('baseService', $di->lazyNew('Service'));
$di->set('baseFlow', $di->lazyNew('Flow'));
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.
class Flow
{
public function __construct(Service $service)
{
$this->service = $service;
}
public function setSomething(Something $something)
{
// other dependency
}
public function showMessage()
{
echo "Inside service";
}
}
Now you can define like
$di->params['Flow']['service'] = $di->lazyNew('Service');
$di->setters['Flow']['setSomething'] = $di->lazyNew('Something');
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.
I noticed someone dislike the answer. You are free to do it, but provide a better answer or edit the answer or write comments what can be improved.