æå°ã®DIã³ã³ãã in PHP
DIã³ã³ããããªã«ãã大仰ãªãã®ã¨ãã¦åéãããã¦ãããããªæ°ãããã®ã§ãæ©è½ã極éã¾ã§åãè½ã¨ããæå°ã®DIã³ã³ãããæ¸ããã
ããã«ã¯AOPã¯å½ç¶ãªãããè¨å®ãã¡ã¤ã«ãªã©ããªãã
<?php // DIContainer.php class DIContainer { protected $componentFactory; function __construct(ComponentFactory $c) { $this->componentFactory = $c; $c->accept($this); } function get($name) { $name = strtolower($name); if (!isset($this->objects[$name])) { $this->objects[$name] = $this->componentFactory->get($name); } return $this->objects[$name]; } } abstract class ComponentFactory { protected $container; function get($name) { return $this->{'build' . $name}(); } function accept(DIContainer $c) { $this->container = $c; } }
é常ã«çãã§ããã
ãã®ã³ã³ãããã©ã使ãã
PDOã®ã¤ã³ã¹ã¿ã³ã¹ã管çããã·ã³ãã«ãªä¾ãç¨æããã
<?php include_once dirname(__FILE__) . '/DIContainer.php'; class MyComponentFactory extends ComponentFactory { function buildConfig() { $config = new stdClass(); $config->db = 'mysql'; $config->dbname = 'hoge'; $config->host = 'localhost'; $config->user = 'dbusername'; $config->password = 'dbpassword'; return $config; } function buildPDO() { $config = $this->container->get('config'); $dsn = "{$config->db}:dbname={$config->dbname};host={$config->host}"; $pdo = new PDO($dsn, $config->user, $config->password); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); return $pdo; } } $container = new DIContainer(new MyComponentFactory); // ãªãã¸ã§ã¯ããã³ã³ããããåãåºã $pdo = $container->get('pdo');
DIã³ã³ããã®å©ç¹ã®ä¸ã¤ã¨ãã¦ããã¸ãã¯ãå«ã¾ãªãã¤ã³ã¹ã¿ã³ã¹ã®çæãå¼ãåãã¦ãããã¨ããç¹ãæããããã
ãã®ã³ã³ããã ã¨DIContainer::getã¡ã½ããã§å¾ãããã®ã¯ã·ã³ã°ã«ãã³ãªãªãã¸ã§ã¯ãã®ã¿ã ãããã£ã¨æ©è½ãæã¤DIã³ã³ãããªãgetãããã³ã«æ°ããã¤ã³ã¹ã¿ã³ã¹ãå¾ããã¨ãããããªãã¨ãã§ããã ããã
DIã¨ããåèªã¯æ¥æ¬èªã«ç´ãã¦ãä¾åæ§ã®æ³¨å
¥ã¨ããæ½è±¡çãªè¨èã«ãªãã®ã§åã£æããããªãããããè¾ãã
ã¾ããã¦ã§ãã«è»¢ãã£ã¦ãDIã«é¢ããæç« ãä¸è¬ã®ãã¶ã¤ã³ãã¿ã¼ã³ã«é¢ããæç« ãªã©ã¨æ¯ã¹ã¦æ½è±¡çã§é£ãããã®ãå¤ãã
ããDIã³ã³ããèªä½ã¯ãããªã«è¤éã§ãããè¾ããã¨ããã£ã¦ããããã§ã¯ãªãã
æåã®åã£æããã¨ãã¦ã¯ãDIã³ã³ããã¯ã¤ã³ã¹ã¿ã³ã¹ã®ç®¡çããã£ã¦ããã便å©ãªå¥´ããããã®èªèã§ããã¨æãã
DIã³ã³ããã§ã¯ã©ã¹å士ãççµåã«ããä¾ã¯ãã¾ãå¾ã®ã¨ã³ããªã§ç¤ºãã