【问题标题】:Dependency Injection with Adapter Pattern and Type Hinting使用适配器模式和类型提示的依赖注入
【发布时间】:2018-02-07 13:04:46
【问题描述】:

我正在尝试将类型提示与适配器结合使用。

系统通过不同的服务获取 XML 提要并使用更改更新数据库 - 我正在重构以帮助学习设计模式。

日志接口:

interface LoggerAdapterInterface {
    public function debug($string);
    public function info($string);
    public function error($string);
}

MonoLog 适配器

class MonoLogAdapter implements LoggerAdapterInterface
{
    public $logger;

    public function __construct(\Monolog\Logger $logger)
    {
        $this->logger = $logger;
    }

    public function debug($string)
    {
        $this->logger->debug($string);
    }

    public function info($string)
    {
        $this->logger->info($string);
    }

    public function error($string)
    {
        $this->logger->error($string);
    }
}

FeedFactory

class FeedFactory
{
    public function __construct()
    {

    }

    public static function build(LoggerAdapter $logger, $feedType)
    {
        // eg, $feedType = 'Xml2u'
        $className = 'Feed' . ucfirst($feedType);

        // eg, returns FeedXml2u
        return new $className($logger);
    }
}

实施

// get mono logger
$monoLogger = $this->getLogger();

// create adapter and inject monologger
$loggerAdapter = new MonoLogAdapter($monoLogger);

// build feed object
$Feed = FeedFactory::build($loggerAdapter, 'Xml2u');

错误

PHP Catchable fatal error:  Argument 1 passed to FeedFactory::build() 
must be an instance of LoggerAdapter, instance of MonoLogAdapter 
given, called in /src/shell/feedShell.php on line 64 and defined in 
/src/Feeds/FeedFactory.php on line 25

所以我正在使用 LoggerAdapter,这样我就不会被绑定到一个日志记录平台。问题是当我创建一个新的 MonoLogger 实例并尝试将其注入工厂时 - PHP 类型提示没有意识到 MonoLogger 实现了 LoggerAdapter。

我在这里做错了吗?

【问题讨论】:

  • 不熟悉PHP语法,但是这里的这一行:public static function build(LoggerAdapter $logger, $feedType),不应该是LoggerAdapterInterface吗?就 OOP 而言,似乎打破了 DIP 取决于类(我假设 LoggerAdapter 是)与您定义的接口。此外,由于错误无法解决,您的MonoLogAdapter 不是LoggerAdapter(但它是LoggerAdapterInterface)。
  • 天啊!对了谢谢。将类型提示更改为 LoggerAdapterInterface 修复了它。啊——所以总是会尝试依赖接口而不是类。
  • 是的,根据 OOP 的依赖注入原则 - 你的应用程序应该包含很多小接口而不是很多硬编码的类。

标签: php oop design-patterns


【解决方案1】:

正如@Ironcache 建议的那样——在build 方法中使用接口作为参数。

public static function build(LoggerAdapterInterface $logger, $feedType)
{
    // eg, $feedType = 'Xml2u'
    $className = 'Feed' . ucfirst($feedType);

    // eg, returns FeedXml2u
    return new $className($logger);
}

注意:还要检查命名空间

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-05
    • 1970-01-01
    • 1970-01-01
    • 2014-01-02
    • 2012-12-29
    • 2020-11-20
    • 2011-11-13
    相关资源
    最近更新 更多