如何制作自动依赖注入器?

时间:2016-03-24 23:34:18

标签: php dependency-injection router service-locator

所以我正在开发一个框架,直到现在我一直在使用一个可以在整个应用程序中静态调用的容器,如下所示:

$router = new Router;
Container::set('router', $router); // this can now be called anywhere

然后在应用程序中的任何其他文件中,可以这样调用:

$router = Container::get('router'); // get the router object with all current data
$router->add_route('/blog', '/Path/To/Controller/Blog@index');

在控制器内,我会:

class Blog_Controller extends Base_Controller
{
    public function __construct()
    {
        $this->blog_model = Container::get('Blog_Model'); // this is instantiated OR if it has already, the container returns the existing object INCLUDING all of its properties thus far.
    }

    public function view($id)
    {
        $this->blog_model->get_post($id);
    }
}

尽管如此,我已经了解了如何在调用控制器时创建注入依赖项的DI容器,如下例所示:

class Blog_Controller extends Base_Controller
{
    public function __construct(Blog_Model $blog_model)
    {
        $this->blog_model = $blog_model; // this is instantiated OR if it has already, the container returns the existing object INCLUDING all of its properties thus far.
    }

    public function view($id)
    {
        $this->blog_model->get_post($id);
    }
}

我无法弄清楚如何有效地这样做。

如何在不必手动执行new Blog_Model的情况下实现Blog_Model(如果已经实例化则返回)。

0 个答案:

没有答案