I am learning Auraphp Di, and I want to write sample code. Suppose I have these files:
public/index.php:
use Aura\Di\ContainerBuilder;
use MyPackage\Component\Authentication\AuthenticateFlow;
require_once dirname(__DIR__) . '/vendor/autoload.php';
$builder = new ContainerBuilder();
$di = $builder->newInstance();
$di->set('authenticateFlow', $di->lazyNew(AuthenticateFlow::class));
$authenticateFlow = $di->get('authenticateFlow');
$authenticateFlow->showName('Belkin');
/src/Components/Authentication/AuthenticationFlow.php:
namespace MyPackage\Components\Authentication;
class AuthenticationFlow
{
public function showName($name)
{
echo $name;
}
}
This is working fine. Now suppose I have another class (/src/Components/Authentication/Filter.php), which has a method called filterInput:
namespace MyPackage\Components\Authentication;
class Filter
{
public function filterInput($input)
{
return htmlspecialchars($input);
}
}
How can I inject Filter to AuthenticationFlow, to use filterInput() method? I wanna have something like this in AuthenticationFlow::showName():
echo $this->filter->filterInput($name);
I am aware that I need to inject Filter class in AuthenticationFlow constructor, but I don't know if I can use the container built in the index.php or not. If I need to create another container in AuthenticationFlow, how index.php would be aware of it?
Your application need to make use of the di container heavily in-order to inject the necessary dependencies. This is not the case of Aura.
Let us step back and look what you would do if you don't use a container.
In-order to make use of
Filterobject insideAuthenticationFlow, you need to inject theFilterobject either via constructor or a setter method. In the example below I am making use of constructor injection.So you will create an object of
AuthenticationFlowas below.In the case of Aura.Di, you may do something like
This will not be true, in an application. You may need
AuthenticateFlowon a differentHelloController::class.So in that case,
HelloController::classneed to be instantiated via the di itself. Else the dependencies will not be injected automatically.You can extend the
Aura\Di\ContainerConfigand define services in multiple classes.Example :
Now your index.php will look like,
As I mentioned in previous answer, I recommend you go through the docs first. It will really help you in long run.