Is it dependency injection and is it a bad practice?

后端 未结 2 592
名媛妹妹
名媛妹妹 2021-02-06 03:18

I have a small framework and I coded it like this. I\'m not sure if it is called dependency injection or not. I don\'t know if it is like a design pattern or not. I also don\'t

2条回答
  •  醉梦人生
    2021-02-06 04:03

    1. Your FrameWork_Engine_Model is a registry (Registry Pattern). Injecting the registry as dependency into all objects is kind of a misunderstood dependency injection. Technically it is DI, but you create a dependency from everything to everything and also take away the flexibility that DI should offer.
    2. If your FrameWork_Engine_Model was meant to instantiate services and manage their dependencies, you could change it to an Inversion of Control Container (typical pattern related to DI)
    3. No, not in general.

    I won't argue your choice of class names and the responsibilities of your services and controllers, as I don't think it is within scope of this question. Just a remark: it looks like your controllers do too much. If you are interested in clean code, you might want to have a look at the Single Responsibility Principle and keep your controllers "thin", moving business logic and database queries to a service layer and output mechanisms like bbcode to views.

    So, back to your example and how to change it to a sensible usage of Dependency Injection. A primitive IoC container could look like that:

    public function createRegisterController()
    {
        $controller = new RegisterController();
        $controller->setImage($this->getImageService());
        // ...
        return $controller;
    }
    public function getImageService()
    {
        if ($this->imageService === null) {
            $this->imageService = new Image();
            // inject dependencies of Image here
        }
        return $this->imageService;
    }
    

    The important point here is: Only inject the dependencies that are needed. And don't create a bunch of global variables disguised as DI.

提交回复
热议问题