続・設計に関して(DI)
PHPでインターフェイスを使う場合にこうしたらいいんじゃね?
というのがひとまず見えたので報告。
まず、インターフェイスの存在価値は非常に大きい。
PHP5に感謝。
スクリプト言語ということを考えると、
これでテストも出来るし、でいいのかと思う。
まず、本体を作る。
-
-
-
- Server.php --------
-
-
interface Interface {
function method01();
function method02();
}
class Server {
private $intf;
function __construct(Interface $intf) {
$this->intf = $intf;
}
function execute() {
$this->intf->method01();
$this->intf->method02();
}
}
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
次に実行するスクリプトを作る。
-
-
-
- ServerRunner.php --
-
-
class InterfaceImpl implements Interface {
public function method01() {
}
public function method02() {
}
}
$server = new Server(new InterfaceImpl());
$server->execute();
−−−−−−−−−−−−−−−−−−−
次にテストを作る
(実際はphpunitとかで作る)
-
-
-
- ServerTest.php ----
-
-
class TestInterface implements Interface {
public function method01() {
}
public function method02() {
}
}
//テスト処理
−−−−−−−−−−−−−−−−−−−
フレームワークと絡めると、
やっぱりDIコンテナ or Factoryが必要になるけど、
生PHPでやるならこれでもいいかな。