Skip to content

Instantly share code, notes, and snippets.

@AlexGalhardo
Created August 24, 2019 21:05
Show Gist options
  • Select an option

  • Save AlexGalhardo/12af081c1a1c768665ddac1af2ceba74 to your computer and use it in GitHub Desktop.

Select an option

Save AlexGalhardo/12af081c1a1c768665ddac1af2ceba74 to your computer and use it in GitHub Desktop.
  • Utilizado quando é necessário manter baixo o nível de acoplamento entre diferentes módulos de um sistema.
  • Nesta solução as dependências entre os módulos não são definidas programaticamente, mas sim pela configuração de uma infraestrutura de software (container) que é responsável por "injetar" em cada componente suas dependências declaradas.
  • A Injeção de dependência se relaciona com o padrão Inversão de controle mas não pode ser considerada um sinônimo deste.
  • Alguns dos frameworks mais utilizados que fazem uso de injeção de dependência são o Spring, o Laravel e o AngularJS.
<?php

class YouTube implements VideoServiceInterface {

	private $url;

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

	public function getEMBED(){
		return '<iframe>'.$this->url .'</iframe>';
	}
}

class Vimeo implements VideoServiceInterface {

	private $url;

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

	public function getEMBED(){
		return '<video>'.$this->url .'</video>';
	}
}

/**
 * JEITO ANTIGO DE SE FAZER
 * NÃO USANDO DESIGN PATTERN
 *
 * EXTREMAMENTE NÃO RECOMENDADO FAZER DESTE MODO
 */
class Aula {

	private $video;

	public function __construct($vide_type, $url){
		if($video_type == 'YouTube'){
			$video = new YouTube($url);
		} else {
			$video = new Vimeo($url);
		}
	}
}


/**
 * MODO CORRETO COM INJEÇÃO DE DEPENDÊNCIA
 */
interface VideoServiceInterface {
	public function getEMBED();
}

class Aula implements VideoServiceInterface {

	private $video;

	public function __construct(VideoServiceInterface $video){
		$this->video = $video;
	}

	public function getVideoHTML(){
		return $this->video->getEMBED();
	}
}

$aula = new Aula(new Youtube('123'));
echo "HTML: " . $aula->getVideoHTML();
``
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment