(DI)为什么我不能在PHP代码中这样做

(DI)为什么我不能在PHP代码中这样做,php,dependency-injection,Php,Dependency Injection,我试图理解为什么我不能在代码中这样做 <?php Class Model { protected static function insert( Entity $entity ) { # some codes to insert data in the database } } 即使用户实体在更改方法签名时扩展了实体: protected static function insert( Entity $entity ) 致: Model和

我试图理解为什么我不能在代码中这样做

<?php
Class Model
{ 
    protected static function insert( Entity $entity )
    {
          # some codes to insert data in the database
    }
}

即使用户实体在更改方法签名时扩展了实体:

 protected static function insert( Entity $entity )
致:

Model和UserModel不再兼容。您可以这样做:

protected static function insert(Entity $entity)
{
    if (!$entity instanceof UserEntity) {
        return \InvalidArgumentException('Entity must be a UserEntity');
    }
    ...
}
有些人可能会争辩说,通过要求子对象而不是定义的子对象来打破契约违反了接口隔离原则。在任何情况下,方法都不再匹配,因为方法表明它不再只需要实体,因此可能不兼容

编辑:目前有一个关于你尝试做什么的建议。它被称为

protected static function insert( UserEntity $entity ) 
protected static function insert(Entity $entity)
{
    if (!$entity instanceof UserEntity) {
        return \InvalidArgumentException('Entity must be a UserEntity');
    }
    ...
}