To install
composer require php-di/php-di
Usage
<?php
require './vendor/autoload.php';
class Speaker
{
public function say($content)
{
echo "want to say:", $content, "\n";
}
}
class Meeting
{
private $speaker;
public function __construct(Speaker $speaker)
{
$this->speaker = $speaker;
}
public function broadCast($content)
{
$this->speaker->say($content);
}
}
//automatically inject speaker into meeting
$container = new DI\Container();
$meeting = $container->get('Meeting');
$meeting->broadCast("Hell World");
/**
* the above codes are the same as the following
* $speaker = new Speaker();
* $meeting = new Meeting($speaker);
* $meeting->broadCast("Hello World 2");
*/
No comments:
Post a Comment