designModeDemo/demo/Structural/DependencyInjection/Run.php

45 lines
1.5 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
namespace demo\Structural\DependencyInjection;
class Run extends \bin\Design
{
/**
* 用松散耦合的方式来更好的实现可测试、可维护和可扩展的代码。
*
* 依赖注入模式依赖注入Dependency Injection是控制反转Inversion of Control的一种实现方式。
* 要实现控制反转,通常的解决方案是将创建被调用者实例的工作交由 IoC 容器来完成,然后在调用者中注入被调用者(通过构造器 / 方法注入实现),
* 这样我们就实现了调用者与被调用者的解耦,该过程被称为依赖注入。
*
* DatabaseConfiguration 被注入 DatabaseConnection 并获取所需的 $config 。
* 如果没有依赖注入模式, 配置将直接创建 DatabaseConnection 。这对测试和扩展来说很不好。
*
* @inheritDoc
*/
public function setDesignName() : string
{
return '依赖注入模式Dependency Injection';
}
/**
* @inheritDoc
*/
public function setDesignRefUrl() : string
{
return 'https://learnku.com/docs/php-design-patterns/2018/DependencyInjection/1501';
}
/**
* @inheritDoc
*/
public function main()
{
// 设置配置信息
$config = new DatabaseConfiguration('localhost', 3306, 'domnikl', '1234');
// 格式化配置信息
$connection = new DatabaseConnection($config);
dump($connection->getDsn());
}
}