Skip to main content

Dependency Injection

Dependency injection is a programming technique that makes a class independent of its dependencies. It achieves that by decoupling the usage of an object from its creation.


Example
Setup/Dependency:
  • composer require symfony/dependency-injection
  • composer require symfony/yaml
  • composer require symfony/config
  • Create folder "src"
  • Add entry in composer.json "autoload":{"psr-4"{"DI\\": "src/"}
  • and then run composer dump-autoload -o

File: /Src/Mail.php
<?php
namespace DI;
class Mail{
    private $cc;
    function __construct($fromname,$fromemail)
    {
        $this->fromname = $fromname;
        $this->fromemail = $fromemail;
    }
    function sendMail($to,$subject,$message)
    {
         $headers = "MIME-Version: 1.0" . "\r\n";
         $headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
         // More headers
         $headers .= 'From: '.$this->fromemail.'<'.$this->fromemail.'>' . "\r\n";
         mail($to,$subject,$message,$headers);
    }
}


File: /src/Notification.php

<?php
namespace DI;


class Notification{
    function __construct(Mail $mail)
    {
        $mail->sendMail("shanky@tech.com","Test Class","Welcome to Dependency Injection course.");
    }

 }


File: /index.php
<?php
require_once('vendor/autoload.php');
use DI\Mail;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\Loader\YamlFileLoader;

$container->setParameter('mailer.from_name', 'sendmail');
$container->setParameter('mailer.from_email', 'sendmail');
$container->register('mail', 'DI\Mail')->addArgument('%mailer.from_name%','%mailer.from_email%');;
$container->register('notification', 'DI\Notification')->addArgument(new Reference('mail'));


Comments

Popular posts from this blog

Custom Sorting Array List in PHP

 <?php $order = array("Z","Srilanka","34", "Canada", "India", "USA"); $array = array(     array('id' => 7867867, 'title' => 'USA'),     array('id' => 3452342, 'title' => 'India'),     array('id' => 1231233, 'title' => 'Srilanka'),     array('id' => 5867867, 'title' => 'Z'), ); usort($array, function ($a, $b) use ($order) {     $pos_a = array_search($a['title'], $order);     $pos_b = array_search($b['title'], $order);     return $pos_a - $pos_b; }); print_r($array); ?>

simple recursive function to copy entire directories

<?php function recurse_copy ( $src , $dst ) {     $dir = opendir ( $src );     @ mkdir ( $dst );     while( false !== ( $file = readdir ( $dir )) ) {         if (( $file != '.' ) && ( $file != '..' )) {             if ( is_dir ( $src . '/' . $file ) ) {                 recurse_copy ( $src . '/' . $file , $dst . '/' . $file );             }             else {                 copy ( $src . '/' . $file , $dst . '/' . $file );             }         }     }     closedir ( $dir ); } ?>