31
31

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

DI(依存性注入)がいみわからん

Posted at
interface ILogger{
	/**
	 * @param String テキスト
	 */
	public function show(string $string);
}

class BrowserLogger implements ILogger{
	/**
	 * @Override
	 */
	public function show(string $string){
		print($string . '<br />');
	}
}
class ErrorlogLogger implements ILogger{
	/**
	 * @Override
	 */
	public function show(string $string){
		error_log($string);
	}
}

class HelloWorld{
	private $logger;
	/**
	 * @param Logger
	 */
	public function __construct(ILogger $logger){
		$this->logger = $logger;
	}

	/**
	 * @param String $string
	 */
	public function show(string $string){
		$this->logger->show($string);
	}
}

$helloWorld1 = new HelloWorld(new BrowserLogger());
$helloWorld1->show('hello, world');

$helloWorld2 = new HelloWorld(new ErrorlogLogger());
$helloWorld2->show('hello, world');

最低限の概念だけ実装したらこんなかんじだと思うんだけど、
で、だからこれがどうしたんだ、という気がしてならない。
だってみんな普通public function setPdo(PDO $pdo){ $this->pdo=$pdo; }とかやるよね?
その程度ことをわざわざDIとか言ってるのか?
PDOはInterfaceじゃないけど、かわりにabstract class PDOInterface extends PDO{}とか書いとけば、まあだいたい同じ意味になるだろう。

31
31
19

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
31
31

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?