SlideShare ist ein Scribd-Unternehmen logo
1 von 34
Downloaden Sie, um offline zu lesen
Dependency Injection
 Reinventing how you manage PHP classes
What is DI?




              DI?
The Really Short Version

 Dependency Injection means giving an object its
      instance variables. Really. That's it.

                                      - James Shore
Why This Kolaveri DI?
Why This Kolaveri DI?


 CHANGE
Why DI?
•   Maintainable

•   Extendible

•   Flexible

•   Configurable

•   Testable

•   Reusable

•   Interoperable
A Real Life Example
Don’t Panic!
“Dependency Injection” is a 25-dollar
    term for a 5-cent concept.
A PHP Example
class MySqlDB {

     private $_link;

     public function __construct($host, $username, $password, $database) {
         $this->_link = mysql_connect($host, $username, $password);
         mysql_select_db($database);
     }

     public function insert($data, $table) {
         array_map('mysql_real_escape_string', $data);

         $query = 'INSERT INTO `' . $table .
             '` (`' . implode('`,`', array_keys($data)) . '`)' .
             'VALUES ("' . implode('","', $data) . '" )';

         return mysql_query($query, $this->_link);
     }

    // ...

}
define('MYSQL_HOST', 'localhost');
define('MYSQL_USER', 'root');
define('MYSQL_PASS', '');
define('MYSQL_DB', 'test');

class User {

    private $_db;
    private $_info = array();

    public function __construct() {
        $this->_db = new MySqlDB(MYSQL_HOST, MYSQL_USER, MYSQL_PASS,
                                 MYSQL_DB);
    }

    public function register($name, $email, $age, $sex) {
        $this->_info = compact('name', 'email', 'age', 'sex');
        $this->_db->insert($this->_info, 'users');
    }

    // ...
}

$user = new User();
$user->register('Tasneem', 'tasmee@fb.me', 18, 'female');
Options
// You can hardcode it
public function __construct() {
    $this->_db = new MySqlDB('localhost', 'root', '', 'test');
}



// You can configure it with an array
public function __construct($config) {
    $this->_db = new MySqlDB($config['host'], $config['user'],
                            $config['pass'], $config['db']);
}



// And, What we saw earlier
public function __construct() {
    $this->_db = new MySqlDB(MYSQL_HOST, MYSQL_USER, MYSQL_PASS,
                             MYSQL_DB);
}
What if I want to use a different
database like MongoDB or SQLite
Hey wait, I can improve it!
class User {

    protected $_db;
    protected $_info = array();

    public function __construct() {
        $registry = RegistrySingleton::getInstance();
        $this->_db = $registry->database;
    }

    public function register($name, $email, $age, $sex) {
        $this->_info = compact('name', 'email', 'age', 'sex');
        $this->_db->insert($this->info, 'users');
    }

    // ...

}

$user = new User();
$user->register('Tasneem', 'tasmee@fb.me', 18, 'female');
Smart Huh???
So, now User depends
      on Registry
Let’s do it with DI
class User {

    protected $_db;
    protected $_info = array();

    public function __construct($database) {
        $this->_db = $database;
    }

    public function register($name, $email, $age, $sex) {
        $this->_info = compact('name', 'email', 'age', 'sex');
        $this->_db->insert($this->_info, 'users');
    }

    // ...

}

$mysql = new MySqlDB('localhost', 'root', '', 'test');
$user = new User($mysql);
$user->register('Tasneem', 'tasmee@fb.me', 18, 'female');
th ere  are
 But
        ro oms  for
st ill
   im pro vem ent
Interface
Ever hear
          d of
Type Hint
          ing
Type Hinting
        Since PHP 5.1
public function test(OtherClass $otherClass) {

}

public function testInterface(Interface $interface) {

}

public function testArray(array $inputArray) {

}
interface Database {
    public function insert(array $data, $table);
}

class User {

    protected $_db;
    protected $_info = array();

    public function __construct(Database $database) {
        $this->_db = $database;
    }

    public function register($name, $email, $age, $sex) {
        $this->_info = compact('name', 'email', 'age', 'sex');
        $this->_db->insert($this->_info, 'users');
    }

    // ...

}

$mysql = new MySqlDB('localhost', 'root', '', 'test');
$user = new User($mysql);
$user->register('Tasneem', 'tasmee@fb.me', 18, 'female');
MySQL
class MySqlDB implements Database {

     protected $_link;

     public function __construct($host, $username, $password, $database) {
         $this->_link = mysql_connect($host, $username, $password);
         mysql_select_db($database);
     }

     public function insert(array $data, $table) {
         array_map('mysql_real_escape_string', $data);

         $query = 'INSERT INTO `' . $table .
             '` (`' . implode('`,`', array_keys($data)) . '`)' .
             'VALUES ("' . implode('","', $data) . '" )';

         return mysql_query($query, $this->_link);
     }

    // ...
}
MongoDB
class MongoDB implements Database {

    // ...

     public function insert(array $data, $table) {
         // Save the passed array using MongoDB
     }

    // ...

}

$mongoDb = new MongoDB('localhost', 'root', '', 'test');
$user = new User($mongoDb);
$user->register('Tasneem', 'tasmee@fb.me', 18, 'female');
SQLite
class SQLiteDB implements Database {

    // ...

     public function insert(array $data, $table) {
         // Save the passed array using SQLite
     }

    // ...

}

$sqlite = new SQLiteDB('app.db', 'test');
$user = new User($sqlite);
$user->register('Tasneem', 'tasmee@fb.me', 18, 'female');
TestDB
class TestDB implements Database {

    protected $_data = array();

    public function insert(array $data, $table) {
        $this->_data[$table] = $data;
    }

    public function get($table) {
        return $this->_data[$table];
    }

}

$fakeDb = new TestDB();
$user = new User($fakeDb);
$user->register('Tasneem', 'tasmee@fb.me', 18, 'female');
print_r($fakeDb->get('users'));
DI Contai
          ner
Twittee
   A DI Container in a Tweet

using the power of                           PHP 5.3
class Container {
    protected $s=array();
    function __set($k, $c) { $this->s[$k]=$c; }
    function __get($k) { return $this->s[$k]($this); }
}
Container
$c = new Container();

$c->mysql = function ($c) {
    return new MySqlDB('localhost', 'root', '', 'test');
}

$c->user = function ($c) {
    $db = $c->mysql;
    return new User($db);
}

// When you need a user
$user = $c->user;

// Instead of
$user = new User();
More...
http://components.symfony-project.org/dependency-injection/

                http://pimple.sensiolabs.org/

                     http://twittee.org/
Question?
Thank
 You


                @rifat
         rifat@facebook.com
          http://VistaArc.com/
        http://OmicronLab.com/

Weitere ähnliche Inhalte

Was ist angesagt?

Internationalizing CakePHP Applications
Internationalizing CakePHP ApplicationsInternationalizing CakePHP Applications
Internationalizing CakePHP ApplicationsPierre MARTIN
 
Zf Zend Db by aida
Zf Zend Db by aidaZf Zend Db by aida
Zf Zend Db by aidawaraiotoko
 
Lithium: The Framework for People Who Hate Frameworks
Lithium: The Framework for People Who Hate FrameworksLithium: The Framework for People Who Hate Frameworks
Lithium: The Framework for People Who Hate FrameworksNate Abele
 
Decouple Your Code For Reusability (International PHP Conference / IPC 2008)
Decouple Your Code For Reusability (International PHP Conference / IPC 2008)Decouple Your Code For Reusability (International PHP Conference / IPC 2008)
Decouple Your Code For Reusability (International PHP Conference / IPC 2008)Fabien Potencier
 
The Origin of Lithium
The Origin of LithiumThe Origin of Lithium
The Origin of LithiumNate Abele
 
Dependency Injection IPC 201
Dependency Injection IPC 201Dependency Injection IPC 201
Dependency Injection IPC 201Fabien Potencier
 
The Zen of Lithium
The Zen of LithiumThe Zen of Lithium
The Zen of LithiumNate Abele
 
PHP 5.3 and Lithium: the most rad php framework
PHP 5.3 and Lithium: the most rad php frameworkPHP 5.3 and Lithium: the most rad php framework
PHP 5.3 and Lithium: the most rad php frameworkG Woo
 
Lecture6 display data by okello erick
Lecture6 display data by okello erickLecture6 display data by okello erick
Lecture6 display data by okello erickokelloerick
 
The State of Lithium
The State of LithiumThe State of Lithium
The State of LithiumNate Abele
 
Everything About PowerShell
Everything About PowerShellEverything About PowerShell
Everything About PowerShellGaetano Causio
 
Doctrine For Beginners
Doctrine For BeginnersDoctrine For Beginners
Doctrine For BeginnersJonathan Wage
 
Doctrine MongoDB Object Document Mapper
Doctrine MongoDB Object Document MapperDoctrine MongoDB Object Document Mapper
Doctrine MongoDB Object Document MapperJonathan Wage
 
ZendCon2010 Doctrine MongoDB ODM
ZendCon2010 Doctrine MongoDB ODMZendCon2010 Doctrine MongoDB ODM
ZendCon2010 Doctrine MongoDB ODMJonathan Wage
 
Dependency injection in PHP 5.3/5.4
Dependency injection in PHP 5.3/5.4Dependency injection in PHP 5.3/5.4
Dependency injection in PHP 5.3/5.4Fabien Potencier
 
Dependency injection-zendcon-2010
Dependency injection-zendcon-2010Dependency injection-zendcon-2010
Dependency injection-zendcon-2010Fabien Potencier
 

Was ist angesagt? (20)

Internationalizing CakePHP Applications
Internationalizing CakePHP ApplicationsInternationalizing CakePHP Applications
Internationalizing CakePHP Applications
 
Zf Zend Db by aida
Zf Zend Db by aidaZf Zend Db by aida
Zf Zend Db by aida
 
Mysql & Php
Mysql & PhpMysql & Php
Mysql & Php
 
Lithium: The Framework for People Who Hate Frameworks
Lithium: The Framework for People Who Hate FrameworksLithium: The Framework for People Who Hate Frameworks
Lithium: The Framework for People Who Hate Frameworks
 
Decouple Your Code For Reusability (International PHP Conference / IPC 2008)
Decouple Your Code For Reusability (International PHP Conference / IPC 2008)Decouple Your Code For Reusability (International PHP Conference / IPC 2008)
Decouple Your Code For Reusability (International PHP Conference / IPC 2008)
 
Php 101: PDO
Php 101: PDOPhp 101: PDO
Php 101: PDO
 
The Origin of Lithium
The Origin of LithiumThe Origin of Lithium
The Origin of Lithium
 
Dependency Injection IPC 201
Dependency Injection IPC 201Dependency Injection IPC 201
Dependency Injection IPC 201
 
The Zen of Lithium
The Zen of LithiumThe Zen of Lithium
The Zen of Lithium
 
Drupal 8 database api
Drupal 8 database apiDrupal 8 database api
Drupal 8 database api
 
Dependency Injection
Dependency InjectionDependency Injection
Dependency Injection
 
PHP 5.3 and Lithium: the most rad php framework
PHP 5.3 and Lithium: the most rad php frameworkPHP 5.3 and Lithium: the most rad php framework
PHP 5.3 and Lithium: the most rad php framework
 
Lecture6 display data by okello erick
Lecture6 display data by okello erickLecture6 display data by okello erick
Lecture6 display data by okello erick
 
The State of Lithium
The State of LithiumThe State of Lithium
The State of Lithium
 
Everything About PowerShell
Everything About PowerShellEverything About PowerShell
Everything About PowerShell
 
Doctrine For Beginners
Doctrine For BeginnersDoctrine For Beginners
Doctrine For Beginners
 
Doctrine MongoDB Object Document Mapper
Doctrine MongoDB Object Document MapperDoctrine MongoDB Object Document Mapper
Doctrine MongoDB Object Document Mapper
 
ZendCon2010 Doctrine MongoDB ODM
ZendCon2010 Doctrine MongoDB ODMZendCon2010 Doctrine MongoDB ODM
ZendCon2010 Doctrine MongoDB ODM
 
Dependency injection in PHP 5.3/5.4
Dependency injection in PHP 5.3/5.4Dependency injection in PHP 5.3/5.4
Dependency injection in PHP 5.3/5.4
 
Dependency injection-zendcon-2010
Dependency injection-zendcon-2010Dependency injection-zendcon-2010
Dependency injection-zendcon-2010
 

Ähnlich wie Dependency Injection

The History of PHPersistence
The History of PHPersistenceThe History of PHPersistence
The History of PHPersistenceHugo Hamon
 
Rich domain model with symfony 2.5 and doctrine 2.5
Rich domain model with symfony 2.5 and doctrine 2.5Rich domain model with symfony 2.5 and doctrine 2.5
Rich domain model with symfony 2.5 and doctrine 2.5Leonardo Proietti
 
Adding Dependency Injection to Legacy Applications
Adding Dependency Injection to Legacy ApplicationsAdding Dependency Injection to Legacy Applications
Adding Dependency Injection to Legacy ApplicationsSam Hennessy
 
Can't Miss Features of PHP 5.3 and 5.4
Can't Miss Features of PHP 5.3 and 5.4Can't Miss Features of PHP 5.3 and 5.4
Can't Miss Features of PHP 5.3 and 5.4Jeff Carouth
 
Your code sucks, let's fix it - DPC UnCon
Your code sucks, let's fix it - DPC UnConYour code sucks, let's fix it - DPC UnCon
Your code sucks, let's fix it - DPC UnConRafael Dohms
 
DrupalCamp Foz - Novas APIs Drupal 7
DrupalCamp Foz - Novas APIs Drupal 7DrupalCamp Foz - Novas APIs Drupal 7
DrupalCamp Foz - Novas APIs Drupal 7chuvainc
 
laravel tricks in 50minutes
laravel tricks in 50minuteslaravel tricks in 50minutes
laravel tricks in 50minutesBarang CK
 
50 Laravel Tricks in 50 Minutes
50 Laravel Tricks in 50 Minutes50 Laravel Tricks in 50 Minutes
50 Laravel Tricks in 50 MinutesAzim Kurt
 
Virtual Madness @ Etsy
Virtual Madness @ EtsyVirtual Madness @ Etsy
Virtual Madness @ EtsyNishan Subedi
 
How Kris Writes Symfony Apps
How Kris Writes Symfony AppsHow Kris Writes Symfony Apps
How Kris Writes Symfony AppsKris Wallsmith
 
You code sucks, let's fix it
You code sucks, let's fix itYou code sucks, let's fix it
You code sucks, let's fix itRafael Dohms
 
Migrating to dependency injection
Migrating to dependency injectionMigrating to dependency injection
Migrating to dependency injectionJosh Adell
 
15. CodeIgniter editarea inregistrarilor
15. CodeIgniter editarea inregistrarilor15. CodeIgniter editarea inregistrarilor
15. CodeIgniter editarea inregistrarilorRazvan Raducanu, PhD
 
WordPress as an application framework
WordPress as an application frameworkWordPress as an application framework
WordPress as an application frameworkDustin Filippini
 
Desarrollo de módulos en Drupal e integración con dispositivos móviles
Desarrollo de módulos en Drupal e integración con dispositivos móvilesDesarrollo de módulos en Drupal e integración con dispositivos móviles
Desarrollo de módulos en Drupal e integración con dispositivos móvilesLuis Curo Salvatierra
 

Ähnlich wie Dependency Injection (20)

The History of PHPersistence
The History of PHPersistenceThe History of PHPersistence
The History of PHPersistence
 
Rich domain model with symfony 2.5 and doctrine 2.5
Rich domain model with symfony 2.5 and doctrine 2.5Rich domain model with symfony 2.5 and doctrine 2.5
Rich domain model with symfony 2.5 and doctrine 2.5
 
Adding Dependency Injection to Legacy Applications
Adding Dependency Injection to Legacy ApplicationsAdding Dependency Injection to Legacy Applications
Adding Dependency Injection to Legacy Applications
 
Can't Miss Features of PHP 5.3 and 5.4
Can't Miss Features of PHP 5.3 and 5.4Can't Miss Features of PHP 5.3 and 5.4
Can't Miss Features of PHP 5.3 and 5.4
 
Your code sucks, let's fix it - DPC UnCon
Your code sucks, let's fix it - DPC UnConYour code sucks, let's fix it - DPC UnCon
Your code sucks, let's fix it - DPC UnCon
 
DrupalCamp Foz - Novas APIs Drupal 7
DrupalCamp Foz - Novas APIs Drupal 7DrupalCamp Foz - Novas APIs Drupal 7
DrupalCamp Foz - Novas APIs Drupal 7
 
Drupal7 dbtng
Drupal7  dbtngDrupal7  dbtng
Drupal7 dbtng
 
laravel tricks in 50minutes
laravel tricks in 50minuteslaravel tricks in 50minutes
laravel tricks in 50minutes
 
50 Laravel Tricks in 50 Minutes
50 Laravel Tricks in 50 Minutes50 Laravel Tricks in 50 Minutes
50 Laravel Tricks in 50 Minutes
 
Virtual Madness @ Etsy
Virtual Madness @ EtsyVirtual Madness @ Etsy
Virtual Madness @ Etsy
 
How Kris Writes Symfony Apps
How Kris Writes Symfony AppsHow Kris Writes Symfony Apps
How Kris Writes Symfony Apps
 
BEAR DI
BEAR DIBEAR DI
BEAR DI
 
You code sucks, let's fix it
You code sucks, let's fix itYou code sucks, let's fix it
You code sucks, let's fix it
 
Oops in php
Oops in phpOops in php
Oops in php
 
Migrating to dependency injection
Migrating to dependency injectionMigrating to dependency injection
Migrating to dependency injection
 
php2.pptx
php2.pptxphp2.pptx
php2.pptx
 
Session8
Session8Session8
Session8
 
15. CodeIgniter editarea inregistrarilor
15. CodeIgniter editarea inregistrarilor15. CodeIgniter editarea inregistrarilor
15. CodeIgniter editarea inregistrarilor
 
WordPress as an application framework
WordPress as an application frameworkWordPress as an application framework
WordPress as an application framework
 
Desarrollo de módulos en Drupal e integración con dispositivos móviles
Desarrollo de módulos en Drupal e integración con dispositivos móvilesDesarrollo de módulos en Drupal e integración con dispositivos móviles
Desarrollo de módulos en Drupal e integración con dispositivos móviles
 

Kürzlich hochgeladen

Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 

Kürzlich hochgeladen (20)

Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 

Dependency Injection

  • 1. Dependency Injection Reinventing how you manage PHP classes
  • 3. The Really Short Version Dependency Injection means giving an object its instance variables. Really. That's it. - James Shore
  • 5. Why This Kolaveri DI? CHANGE
  • 6. Why DI? • Maintainable • Extendible • Flexible • Configurable • Testable • Reusable • Interoperable
  • 7. A Real Life Example
  • 8. Don’t Panic! “Dependency Injection” is a 25-dollar term for a 5-cent concept.
  • 10. class MySqlDB { private $_link; public function __construct($host, $username, $password, $database) { $this->_link = mysql_connect($host, $username, $password); mysql_select_db($database); } public function insert($data, $table) { array_map('mysql_real_escape_string', $data); $query = 'INSERT INTO `' . $table . '` (`' . implode('`,`', array_keys($data)) . '`)' . 'VALUES ("' . implode('","', $data) . '" )'; return mysql_query($query, $this->_link); } // ... }
  • 11. define('MYSQL_HOST', 'localhost'); define('MYSQL_USER', 'root'); define('MYSQL_PASS', ''); define('MYSQL_DB', 'test'); class User { private $_db; private $_info = array(); public function __construct() { $this->_db = new MySqlDB(MYSQL_HOST, MYSQL_USER, MYSQL_PASS, MYSQL_DB); } public function register($name, $email, $age, $sex) { $this->_info = compact('name', 'email', 'age', 'sex'); $this->_db->insert($this->_info, 'users'); } // ... } $user = new User(); $user->register('Tasneem', 'tasmee@fb.me', 18, 'female');
  • 12. Options // You can hardcode it public function __construct() { $this->_db = new MySqlDB('localhost', 'root', '', 'test'); } // You can configure it with an array public function __construct($config) { $this->_db = new MySqlDB($config['host'], $config['user'], $config['pass'], $config['db']); } // And, What we saw earlier public function __construct() { $this->_db = new MySqlDB(MYSQL_HOST, MYSQL_USER, MYSQL_PASS, MYSQL_DB); }
  • 13. What if I want to use a different database like MongoDB or SQLite
  • 14. Hey wait, I can improve it!
  • 15. class User { protected $_db; protected $_info = array(); public function __construct() { $registry = RegistrySingleton::getInstance(); $this->_db = $registry->database; } public function register($name, $email, $age, $sex) { $this->_info = compact('name', 'email', 'age', 'sex'); $this->_db->insert($this->info, 'users'); } // ... } $user = new User(); $user->register('Tasneem', 'tasmee@fb.me', 18, 'female');
  • 17. So, now User depends on Registry
  • 18. Let’s do it with DI
  • 19. class User { protected $_db; protected $_info = array(); public function __construct($database) { $this->_db = $database; } public function register($name, $email, $age, $sex) { $this->_info = compact('name', 'email', 'age', 'sex'); $this->_db->insert($this->_info, 'users'); } // ... } $mysql = new MySqlDB('localhost', 'root', '', 'test'); $user = new User($mysql); $user->register('Tasneem', 'tasmee@fb.me', 18, 'female');
  • 20. th ere are But ro oms for st ill im pro vem ent
  • 22. Ever hear d of Type Hint ing
  • 23. Type Hinting Since PHP 5.1 public function test(OtherClass $otherClass) { } public function testInterface(Interface $interface) { } public function testArray(array $inputArray) { }
  • 24. interface Database { public function insert(array $data, $table); } class User { protected $_db; protected $_info = array(); public function __construct(Database $database) { $this->_db = $database; } public function register($name, $email, $age, $sex) { $this->_info = compact('name', 'email', 'age', 'sex'); $this->_db->insert($this->_info, 'users'); } // ... } $mysql = new MySqlDB('localhost', 'root', '', 'test'); $user = new User($mysql); $user->register('Tasneem', 'tasmee@fb.me', 18, 'female');
  • 25. MySQL class MySqlDB implements Database { protected $_link; public function __construct($host, $username, $password, $database) { $this->_link = mysql_connect($host, $username, $password); mysql_select_db($database); } public function insert(array $data, $table) { array_map('mysql_real_escape_string', $data); $query = 'INSERT INTO `' . $table . '` (`' . implode('`,`', array_keys($data)) . '`)' . 'VALUES ("' . implode('","', $data) . '" )'; return mysql_query($query, $this->_link); } // ... }
  • 26. MongoDB class MongoDB implements Database { // ... public function insert(array $data, $table) { // Save the passed array using MongoDB } // ... } $mongoDb = new MongoDB('localhost', 'root', '', 'test'); $user = new User($mongoDb); $user->register('Tasneem', 'tasmee@fb.me', 18, 'female');
  • 27. SQLite class SQLiteDB implements Database { // ... public function insert(array $data, $table) { // Save the passed array using SQLite } // ... } $sqlite = new SQLiteDB('app.db', 'test'); $user = new User($sqlite); $user->register('Tasneem', 'tasmee@fb.me', 18, 'female');
  • 28. TestDB class TestDB implements Database { protected $_data = array(); public function insert(array $data, $table) { $this->_data[$table] = $data; } public function get($table) { return $this->_data[$table]; } } $fakeDb = new TestDB(); $user = new User($fakeDb); $user->register('Tasneem', 'tasmee@fb.me', 18, 'female'); print_r($fakeDb->get('users'));
  • 29. DI Contai ner
  • 30. Twittee A DI Container in a Tweet using the power of PHP 5.3 class Container { protected $s=array(); function __set($k, $c) { $this->s[$k]=$c; } function __get($k) { return $this->s[$k]($this); } }
  • 31. Container $c = new Container(); $c->mysql = function ($c) { return new MySqlDB('localhost', 'root', '', 'test'); } $c->user = function ($c) { $db = $c->mysql; return new User($db); } // When you need a user $user = $c->user; // Instead of $user = new User();
  • 32. More... http://components.symfony-project.org/dependency-injection/ http://pimple.sensiolabs.org/ http://twittee.org/
  • 34. Thank You @rifat rifat@facebook.com http://VistaArc.com/ http://OmicronLab.com/