我在这里思考一些不同的方法,非常感谢一些输入!我正在考虑以下两个选择.那里有两件事我有疑问.
>是否首选将依赖项注入主“容器”类的构造函数中,或者在容器类中创建新实例?
>在第二个示例中,类的依赖项通过构造函数注入,然后通过类的属性进行维护.然后,当调用方法(route(),render())时,从内部调用依赖项.我从这种方法开始,但现在我更倾向于第一个例子.我认为第一个例子是可取的,但在第二个例子中使用DI方法有什么好处吗?
确实没有必要在课堂上存储任何东西作为财产.我可以重新安排一切使用这种技术而不会有太多麻烦,我想我更喜欢它.这样我也可以将所有工作从构造函数中移出,然后通过方法简单地访问所有内容.我在这里走在正确的轨道上吗?
class App
{
private $config;
private $router;
private $renderer;
public function __construct(IConfig $config, IRouter $router, IRenderer $renderer)
{
$this->config = $config;
$this->router = $router;
$this->renderer = $renderer;
$this->run();
}
public function run()
{
$data = $this->router->route(new Request, $config->routes);
$this->renderer->render($data);
}
}
class App
{
private $config;
private $router;
private $renderer;
public function __construct()
{
$this->config = new Config;
$this->run();
}
public function run()
{
$this->router = new Router(new Request, $config->routes);
$this->router->route();
$this->renderer = new Renderer($this->router->getData());
$this->renderer->render();
}
}
如果觉得《php 松散耦合 PHP依赖注入和松散耦合》对你有帮助,请点赞、收藏,并留下你的观点哦!