【发布时间】: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