I'm trying to understand Dependency injections, and currently working with Symphony DI container.
I managed to get my container working in a very basic way:
Objects are created only when called. for example, if I remove the Database $database
TypeHint from my SystemUser.php class, the database will not load.
How do I handle situations where I want to load a "Customer" class (see App.php) and that customer class needs the database object?
I do not want to create a new object of Customer, just get a reference of it from the container (if created) + have the Database class passed to it. but again, from the container.
Normally I would think that there are some classes which do not need any special objects like Database because they aren't using the database.
So how do I handle a situation where there is a special case where I need to create (or better say, fetch from the container) an object that does use the Database class, and it's far from being passed in a __construct.
This is the exmaple files I am working with:
index.php
require_once 'vendor/autoload.php';
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;
use TestingDI\Database;
use TestingDI\SystemUser;
use TestingDI\Customer;
use TestingDI\App;
$container = new ContainerBuilder();
$container->autowire( Database::class );
$container->autowire( SystemUser::class );
$container->autowire( Customer::class );
$container->autowire( App::class )
->setPublic( true );
$container->compile();
$app = $container->get( App::class );
App.php:
namespace TestingDI;
use TestingDI\SystemUser;
class App {
public $systemUser;
public $customer;
public function __construct(SystemUser $systemUser)
{
dump($this);
$this->systemUser = $systemUser;
$customer = new \TestingDI\Customer();
}
public function __destruct()
{
dump($this);
}
}
SystemUser.php
namespace TestingDI;
use TestingDI\Database;
class SystemUser {
public $db;
public $id;
public function __construct( Database $database )
{
dump($this);
$this->db = $database;
$this->db->changeTest(1);
}
}
Customer.php
namespace TestingDI;
class Customer
{
public $db;
public function __construct( Database $database )
{
$this->db = $database;
dump($this);
$this->db->changeTest(10);
}
}
Database.php
namespace TestingDI;
class Database {
public $pdo = "DATABASE: I'm a pdo instance <br>";
public $test;
public function __construct()
{
dump($this);
}
public function hello()
{
echo "DATABASE: hello database <br>";
}
public function changeTest($msg)
{
$this->test = $msg;
}
}
Aucun commentaire:
Enregistrer un commentaire