Upgrade to Pro — share decks privately, control downloads, hide ads and more …

今こそ理解するDI(Dependency Injection) / Understand De...

今こそ理解するDI(Dependency Injection) / Understand Dependency Injection of PHP

TwitterID:@rukiadia

March 28, 2021
Tweet

More Decks by TwitterID:@rukiadia

Other Decks in Programming

Transcript

  1. “Dependency Injection Principles, Practices, and Patterns” Part 1 Putting Dependency

    Injection on the map “Dependency Injection is a set of software design principles and patterns that enables you to develop loosely coupled code.” 11 DIͷ֓࿦
  2. ྫɿ$BLF1)1ͷϢχοτςετ class ArticlesTableTest extends TestCas e { public $fixtures =

    ['app.Articles'] ; public function setUp( ) { parent::setUp() ; $this->Articles = TableRegistry::getTableLocator()->get('Articles') ; } public function tearDown( ) { TableRegistry::clear() ; } } هࣄͷݕࡧ΍ফڈΛߦ͏ .PEFMςετͷԼ஍
  3. ྫɿ$BLF1)1ͷϢχοτςετʢ੍ޚͷٯసʣ class ArticlesTableTest extends TestCas e { public $fixtures =

    ['app.Articles'] ; public function setUp() { parent::setUp() ; $this->Articles = TableRegistry::getTableLocator()->get('Articles') ; } public function tearDown( ) { TableRegistry::clear() ; } } ४උɺޙ࢝຤ɺςετ࣮ߦͷλΠϛϯάΛ ϑϨʔϜϫʔΫ͕Ѳ͍ͬͯΔ
  4. ྫɿ&NBJMΛૹ৴͢ΔΫϥε class EmailSender { private $mailClient ; public function init(

    ) { // ʮAmazon Simple Email ServiceʯΛ࢖༻ͯ͠ϝʔϧΛѻ͏Ϋϥε $this->mailClient = new AwsSes( ) } public function sendRegisterMail($address, $text ) { $this->mailClient->send($address, $text) ; } } Ұݟɺ໰୊ͳͦ͞͏ʹݟ͑Δ
  5. ྫɿ&NBJMΛૹ৴͢ΔΫϥε class EmailSender { private $mailClient ; public function init(

    ) { // ʮAmazon Simple Email ServiceʯΛ࢖༻ͯ͠ϝʔϧΛѻ͏Ϋϥε $this->mailClient = new AwsSes() // EmailSenderΫϥε͕AwsSesΫϥεʹґଘ͍ͯ͠Δ } public function sendRegisterMail($address, $text ) { $this->mailClient->send($address, $text) ; } }
  6. ྫɿ&NBJMΛૹ৴͢ΔΫϥεɾվ class EmailSender { private $mailClient ; public function __construct($client

    ) { $this->mailClient = $client; // αʔϏεΛѻ͏ΫϥεΛ֎෦͔Βࢦఆ͢ΔΑ͏ʹมߋ } public function sendRegisterMail($address, $text ) { $this->mailClient->send($address, $text) ; } } &NBJM4FOEFSͰ࢖༻͢ΔϝιουΛ JOUFSGBDFΛ࢖༻ͯ͠දݱ
  7. &NBJMΛૹ৴͢ΔΠϯλϑΣʔεྫ interface iEmailClient { public function send($address, $text) ; }

    class AwsSes implements iEmailClient { private $mailClient ; public function __construct( ) { $this->mailClient = new AwsSes() ; } public function send($address, $text){ } } &NBJM4FOEFS͕ґଘ͢Δ෦෼Λ JOUFSGBDFͱͯ͠දݱ͠ɺ ґଘ౓ͷ௿ݮΛਤ͍ͬͯΔ
  8. ࢀߟจݙ • ʮDependency Injection Principles, Practices, and Patternsʯ • https://www.amazon.com/dp/161729473X

    • ※ O’Reilly online learningͰಡΊ·͢ɻ • https://martinfowler.com/bliki/InversionOfControl.html • https://martinfowler.com/articles/injection.html