MVC and dependency injection, forced to use singleton Controller?

久未见 提交于 2019-12-06 02:35:46

Several solutions are possible:

  • forbid controllers to use __construct(): make it private public final, and make controllers override something like init() and call it from the constructor. Then the constructor would inject all the dependencies (reflection? other stuff?), so that they are all ready in init().

  • you can use an existing DI library like PHP-DI (disclaimer: I work on that) that will allow you to define dependencies but have them available in the constructor (magically, yes).

Something like that:

<?php
use DI\Annotations\Inject;

class FooController {
    /**
     * @Inject
     * @var Bar
     */
    private $bar;

    public function __construct() {
        // The dependency is already injected
        $this->bar->sayHello();
    }

    public function setBar(Bar $bar) {
        return $this->bar = $bar;
    }
}

For example that is how I work with Zend Framework 1. I can't use the constructors, so I inject into properties. Here is the ZF1 integration project.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!