简体   繁体   English

PHP依赖注入容器与工厂

[英]PHP Dependency Injection Container With Factory

I'm working with silexphp/Pimple Dependency Injection Containers (DIC) and am unsure how to handle what would be a classic Factory pattern. 我正在使用silexphp/Pimple依赖注入容器(DIC),并且不确定如何处理经典的Factory模式。

Example: 例:

A parent class Animal.php has two child classes called DogAnimal.php and CatAnimal.php . 父类Animal.php有两个名为DogAnimal.phpCatAnimal.php子类。 The number of child classes can grow. 子类的数量可以增长。

In this case I'd want to create a Factory for creating new Animal Objects or children of the Animal class. 在这种情况下,我想创建一个Factory来创建新的Animal对象或Animal类的子对象。 Pimple does allow one to create Factory methods per service. Pimple允许每个服务创建Factory方法。

While using Pimple DIC I don't think I'd want to add each subclass (Dog, Cat, etc) as a service. 在使用Pimple DIC时,我认为我不想将每个子类(Dog,Cat等)添加为服务。 Especially as the list grows. 特别是随着名单的增长。 To me that seems like a misuse of the DIC but perhaps I'm wrong. 对我来说,这似乎是对DIC的滥用,但也许我错了。

Am I correct in assuming that I should be creating an Animal Factory service and using Pimple to inject dependencies to the factory which in turn gets used to create a new Dog or Cat? 我是否正确地假设我应该创建一个动物工厂服务并使用Pimple将依赖关系注入工厂,而工厂又会习惯于创建一个新的Dog或Cat?

Yes, you're right. 你是对的。 You can create a service ( AnimalFactory ) that creates the object you want to use ( DogAnimal , CatAnimal , ...). 您可以创建一个服务( AnimalFactory )来创建您想要使用的对象( DogAnimalCatAnimal ,...)。

A simple example can be: 一个简单的例子可以是:

class AnimalFactory
{
    public function createAnimal($name)
    {
        // some logic here with $name

        $animal = new ...();
        return $animal;
    }
}

$pimple['animal_factory'] = function ($c) {
    return new AnimalFactory();
};

$dog = $pimple['animal_factory']->createAnimal('Dog');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM