在一个中使用两个类:设计错误?

eij*_*eij 1 php design-patterns

我写了这两个简单的加密和解密字符串的类:

Encode.php

    class Encode {
        protected funcion do_encode($string) { .. }
    }


Decode.php

    class Decode {
        protected funcion do_decode($string) { .. }
    }

做的是:

Encrypt.php

    class Encrypt extends Encode, Decode {
        protected $stuff_for_parents;

        function __construct($configs) {
            $this->stuff_for_parents = $configs['SomeConf'];
        }

        public function encode($string) { $this->do_encode($string); }
        public function decode($string) { $this->do_decode($string); }
    }

但是我们不能包含多个类,所以:失败.
现在我的问题是:

  1. 这是一个设计问题吗?因为这种情况对我来说并不奇怪,是吗?
  2. 是否有另一种方法可以让一个对象同时使用不同类中的函数?有点$encrypt->encode($str); $encrypt->decode($str);

JW.*_*JW. 5

如果您希望Encode和Decode成为单独的类,则可以在Encrypt中创建它们的实例.例如:

<?
class Encrypt {
  private $encoder;
  private $decoder;
  public function __construct() {
    $this->encoder = new Encode();
    $this->decoder = new Decode();
  }
  public function encode($string) {
    return $this->encoder->encode($string);
  }
  public function decode($string) {
    return $this->decoder->decode($string);
  }
}
?>
Run Code Online (Sandbox Code Playgroud)

在该示例中,Encode和Decode必须是具体类.但您可能需要考虑使用接口.如果您认为在不同情况下可能需要使用不同类型的Encode和Decode对象,则接口非常有用.例如,您可能拥有TripleDESEncode类和BlowfishEncode类.它们都可以实现一个通用接口,如下所示:

<?
interface IEncode {
  public function encode($string);
}
class TripleDESEncode implements IEncode {
  public function encode($string) {...}
}
class BlowfishEncode implements IEncode {
  public function encode($string) {...}
}
?>
Run Code Online (Sandbox Code Playgroud)

在这种情况下,您可能希望首先创建要使用的特定实例,然后将它们传递给Encrypt的构造函数.这称为依赖注入:

<?
class Encrypt {
  public function __construct(IEncode $encoder, IDecode $decoder) {
    $this->encoder = $encoder;
    $this->decoder = $decoder;
  }
  ...
}

$myEncrypt = new Encrypt(new BlowfishEncode(), new BlowfishDecode());
echo $myEncrypt->encode('test');
?>
Run Code Online (Sandbox Code Playgroud)