PHP code example of yjx / easy-di

1. Go to this page and download the library: Download yjx/easy-di library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

yjx / easy-di example snippets


use EasyDi\Container();

$container = new Container();

use Psr\Container\ContainerInterface;
use EasyDI\Container();

$c = new EasyDI\Container();

// 定义参数
$c->raw('redis.host', "127.0.0.1");

// 使用闭包
$c->set('redis', function(ContainerInterface $c) {
  $redis = new Redis();
  $redis->pconnect($c->get('redis.host'));
  return $redis;
}, [], true);

$reids = $c->get('redis');  // 由于set时第4个参数$shared设置为true, 因此每次获取的都是同一个对象

class Mailer
{
    public function mail($recipient, $content)
    {
        // send an email to the recipient
    }
}

class UserManager
{
    private $mailer;

    public function __construct(Mailer $mailer)
    {
        $this->mailer = $mailer;
    }

    public function register($email, $password)
    {
        // The user just registered, we create his account
        // ...

        // We send him an email to say hello!
        $this->mailer->mail($email, 'Hello and welcome!');
    }
}

$c = new EasyDI\Container();
$userManager = $c->get('UserManager');

// 等价执行
//$mailer = new Mailer();
//$userManager = new UserManager($mailer);

class ClassA
{
    protected $b;
    protected $say;

    public function __construct(ClassB $b, ClassC $c, $say="hello")
    {
        $this->b = $b;
        $this->say = $say;
    }

    public function saySth()
    {
      return "{$this->say} {$this->b->saySth()}";
    }
}

class ClassB
{
    protected $msg;

    public function __construct($msg)
    {
        $this->msg = $msg;
    }

    public function saySth()
    {
        return $this->msg;
    }
}

class ClassC
{
}

// 容器实例化
$c = new EasyDI\Container();

// 最基础的配置方式, 未用到容器的依赖注入特性
$c->set('basic', function () {
    return new ClassA(new ClassB("easy-di"), new ClassC(), "I like");
});
$basicService = $c->get('basic');
echo $basicService->saySth().PHP_EOL;   // 输出: I like easy-di

// 利用容器自动解决依赖
$c->set(ClassB::class, ClassB::class, ['easy-di']);         // 配置ClassB的标量依赖, params 等同配置 ['msg'=>"easy-di"]
$c->set('advance', ClassA::class, [2=>"I really like"]);    // 配置advance服务, params 等同配置 ['say'=>"I really like"]
$advanceService = $c->get('advance');                       // ClassA实例化所需的第2个参数$c由容器自动生成实例
echo $advanceService->saySth().PHP_EOL; // 输出: I really like easy-di