hypario/container

一个简单的容器,类似于PHP-DI

1.1.0 2021-02-09 11:05 UTC

This package is auto-updated.

Last update: 2024-09-09 18:38:54 UTC


README

Build Status Coverage Status

这是什么?

这个库是一个用PHP编写的依赖注入容器。我创建这个库是为了学习和使用PHP-DI作为例子。

如何使用它?

首先,您需要创建一个容器构建器,该构建器将构建您的容器

$builder = new Hypario\Builder();
$container = $builder->build();

然后您可以使用容器来实例化一个类。

例如

class A {
    public function hello() {
        return "Hello World !";
    }
}

$builder = new Hypario\Builder();
$container = $builder->build();

$class = $container->get(A::class);

echo $class->hello(); // output : "Hello World !"

容器将实例化这个类

但如果有构造函数呢?

就像您通常会做的那样,有时您需要为您的类添加构造函数,有不同的可能性

带默认值

有时您需要一个带有构造函数的类,该构造函数具有默认值,没问题,类将以默认值实例化,如下所示

class A {
    
    private $name;

    public function __construct(string $name = "John") {
        $this->name = $name;
    }

    public function hello() {
        return "Hello $this->name !";
    }
}

$builder = new Hypario\Builder();
$container = $builder->build();

$class = $container->get(A::class);
echo $class->hello(); // output : "Hello John !"

带类

有时您的类需要另一个类才能工作,不用担心,这个容器可以实例化需要的类(如果构造函数使用默认值或另一个类!)

class Address {

    public $address;

    public function __construct() {
        $this->address = 'France, Paris 6e'
    }
}

class Person {

    public $name;
    
    public $address;

    public function __construct(Address $address, string $name = 'John') {
        $this->name = $nom;
        $this->address = $address;
    }

    public function hello() {
        return "Hello $this->name, you live in $this->address";
    }

}

$builder = new Hypario\Builder();
$container = $builder->build();

$class = $container->get(Person::class);
echo $class->hello(); // output : "Hello John, you live in France, Paris 6e"

定义

定义是一个数组,您在其中定义容器如何实例化一个类,或者对于特定的词调用哪个函数,从而定义您的类应该如何实例化。

您可能觉得使用容器构建器而不是直接调用容器很奇怪,对吗?事实上,在构建容器之前,您可以向容器构建器定义一些定义,如下所示

$builder = new Hypario\Builder();
$builder->addDefinitions(['foo' => 'bar']);
$container = $builder->build();

echo $container->get('foo'); // output : "bar"

在这里,我将定义用作一个简单的数组,但您可以使用它来实例化需要接口的类

interface testInterface{

    public function hello();

}

class test implements testInterface {

    public $string = "Hello I am the test class";

    public function hello(): string {
        return $this->string;
    }
}

class A {

    public $test;

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

$builder = new Hypario\Builder();
$builder->addDefinitions([
    testInterface::class => test::class
]);
$container = $builder->build();
$class = $container->get(A::class); 
echo $class->test->hello(); // output : "Hello I am the test class

由于定义中指定我们不能获取接口的实例,容器将实例化实现testInterface的test类