I'm trying to implement Symfonys dependency injection container.
I have 2 containers set, one for the database, and one for the system user.
and I'm using "addArgument()
" to both the App
class and SystemUser
class, pushing to App
class a SystemUser
object, and for the SystemUser
class a Database
object.
index.php:
require_once 'vendor/autoload.php';
use TestingDI\App;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;
$containerBuilder = new ContainerBuilder();
$containerBuilder->register('database', '\TestingDI\Database');
$containerBuilder->register('system.user', '\TestingDI\SystemUser')
->addArgument(new Reference('database'));
$containerBuilder->register('app', '\TestingDI\App')
->addArgument(new Reference('system.user'));
$database = $containerBuilder->get('database');
$systemUser = $containerBuilder->get('system.user');
$app = $containerBuilder->get('app');
# Initialize App class
$app = new App();
App.php:
<?php
namespace TestingDI;
use TestingDI\SystemUser;
class App {
public $systemUser;
public function __construct(SystemUser $systemUser)
{
var_dump($systemUser);
}
}
I do see my var_dump result, with the object, but keep getting this error:
PHP Fatal error: Uncaught ArgumentCountError: Too few arguments to function TestingDI\App::__construct(), 0 passed in /www/potato/symfony-di/index.php on line 28 and exactly 1 expected in /www/potato/symfony-di/testingdi/App.php:12
Stack trace:
0 /www/potato/symfony-di/index.php(28): TestingDI\App->__construct()
1 {main} thrown in /www/potato/symfony-di/testingdi/App.php on line 12
These are my other classes:
SystemUser.php
<?php
namespace TestingDI;
use TestingDI\Database;
class SystemUser {
public $db;
public function __construct( Database $database )
{
$this->db = $database;
}
}
Database.php
<?php
namespace TestingDI;
class Database {
public function __construct()
{
}
}