
本文介绍如何利用接口继承与组合设计,让具有不同能力的类既能共享通用契约(如日志记录),又能各自保留特有行为(如设置属性),从而在不修改调用逻辑的前提下支持多态替换与可扩展依赖注入。
在面向对象设计中,接口的核心价值在于定义最小可行契约,而非强制所有实现类具备完全一致的方法集。当你遇到 LogDownloadService 和 LogUserService 都需支持 log(),但后者还需 setAttr() 时,强行让二者共用同一接口(或添加冗余方法)会破坏接口隔离原则(ISP)——这正是你当前困境的根源。
✅ 正确解法是采用接口组合(Interface Composition):将职责正交的能力拆分为独立接口,并按需组合。
1. 拆分关注点:定义细粒度接口
interface SystemLogInterface
{
public function log(string $type): void;
}
interface AttributeConfigurableInterface
{
public function setAttr(mixed $value): void;
}2. 组合契约:创建复合接口(可选但推荐)
// 显式声明“既可日志又可配置属性”的能力
interface LoggableWithAttributesInterface extends SystemLogInterface, AttributeConfigurableInterface
{
}3. 各类按需实现对应接口
class LogDownloadService implements SystemLogInterface
{
public function log(string $type): void
{
// 实现日志逻辑
echo "Download log: {$type}";
}
}
class LogUserService implements LoggableWithAttributesInterface
{
private mixed $attr;
public function setAttr(mixed $value): void
{
$this->attr = $value;
}
public function log(string $type): void
{
echo "User log (attr={$this->attr}): {$type}";
}
}4. 依赖注入时精准声明所需能力
// ✅ 仅需日志能力 → 接受任意 SystemLogInterface 实现
public function processLog(SystemLogInterface $logger): void
{
$logger->log('info');
}
// ✅ 需要日志 + 属性配置 → 接受 LoggableWithAttributesInterface
public function configureAndLog(LoggableWithAttributesInterface $service): void
{
$service->setAttr($this->getAttr());
$service->log('configured');
}
// ✅ 向后兼容:LogUserService 可同时传入以上两个方法
$downloadLogger = new LogDownloadService();
$userLogger = new LogUserService();
$this->processLog($downloadLogger); // ✔️
$this->processLog($userLogger); // ✔️(因实现 SystemLogInterface)
$this->configureAndLog($userLogger); // ✔️(因实现 LoggableWithAttributesInterface)
// $this->configureAndLog($downloadLogger); // ❌ 类型错误:未实现 setAttr()⚠️ 关键注意事项
- 不要为“方便”而污染接口:在 SystemLogInterface 中添加 setAttr() 会导致 LogDownloadService 被迫实现无意义方法,违反 ISP。
- 接口名应体现能力,而非实现类名:SystemLogInterface 是合理命名;避免出现 LogUserServiceInterface 这类紧耦合名称。
- 构造器注入优于运行时配置:虽然题目要求 setAttr() 不在构造器中,但在实际项目中,优先考虑通过构造器注入不可变依赖,提升类的确定性与可测试性。
- 组合优于继承:PHP 不支持多重继承,但允许多重接口实现——这正是组合接口模式天然适用的场景。
通过这种设计,你不仅解决了 foo() 方法因类型变更而需反复修改的问题,更构建了可演进的契约体系:未来若新增 flush() 能力,只需定义 FlushableInterface 并让需要它的类实现即可,完全不影响现有代码。这才是 Clean Code 与 SOLID 原则在真实场景中的落地实践。










