├── .gitignore ├── README.md └── src └── GSoares └── SOLID ├── DependencyInversion ├── Correct.php ├── README.md └── Wrong.php ├── InterfaceSegregation ├── Correct.php ├── README.md └── Wrong.php ├── LiskovSubstitution ├── Correct.php ├── README.md └── Wrong.php ├── OpenClosed ├── Correct.php ├── README.md └── Wrong.php └── SingleResponsability ├── Correct.php ├── README.md └── Wrong.php /.gitignore: -------------------------------------------------------------------------------- 1 | /.settings 2 | /.buildpath 3 | /.project 4 | /index.php 5 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | SOLID 2 | ===== 3 | 4 | Projeto com exemplos em PHP dos Princípios SOLID para maior qualidade em programação. Os exemplos foram escritos em PHP, 5 | pois é a liguagem que trabalho, mas SOLID está relacionado a boas práticas de programação, não estando ligado 6 | diretamente a nenhuma linguagem de programação. 7 | 8 | 9 | * Por que aprender SOLID? 10 | 11 | Porque é uma ótima prática que irá melhorar a qualidade do seu software: 12 | 13 | * Facilitando o entendimento do código. 14 | * Evitando discrepância e redundância. 15 | * Proporcionando mais coesão ao código. 16 | * Melhorando a organização do seu código. 17 | * Eliminando dependências e acoplamentos desnecessárias. 18 | * Padrão conciso: 19 | * Fácil entendimento. 20 | * Fácil manutenção. 21 | * Menor curva de aprendizado. 22 | * Maior produtividade. 23 | * Menos custo. 24 | 25 | * Atalhos 26 | 27 | * [Single Responsability Principle (SRP)](src/GSoares/SOLID/SingleResponsability) 28 | * [Open/Closed Principle (OCP)](src/GSoares/SOLID/OpenClosed) 29 | * [Liskov Substitution Principle (LSP)](src/GSoares/SOLID/LiskovSubstitution) 30 | * [Interface Segregation Principle (ISP)](src/GSoares/SOLID/InterfaceSegregation) 31 | * [Dependency Inversion Principle (DIP)](src/GSoares/SOLID/DependencyInversion) 32 | -------------------------------------------------------------------------------- /src/GSoares/SOLID/DependencyInversion/Correct.php: -------------------------------------------------------------------------------- 1 | powerDevice = $powerDevice; 42 | } 43 | 44 | public function turnOn() 45 | { 46 | if (condition) { //some condition 47 | $this->powerDevice->on(); 48 | } 49 | } 50 | 51 | } -------------------------------------------------------------------------------- /src/GSoares/SOLID/DependencyInversion/README.md: -------------------------------------------------------------------------------- 1 | Dependency Inversion Principle (DIP) 2 | ===== 3 | 4 | A definição de DIP que significa "Inversão de Dependência" afirma que: 5 | 6 | 1) "Módulos de alto nível não devem depender de módulos de baixo nível. Ambos devem depender de abstrações". 7 | 2) "Abstrações não devem depender de detalhes. Detalhes devem depender de abstrações." -------------------------------------------------------------------------------- /src/GSoares/SOLID/DependencyInversion/Wrong.php: -------------------------------------------------------------------------------- 1 | computer->on(); 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/GSoares/SOLID/InterfaceSegregation/Correct.php: -------------------------------------------------------------------------------- 1 | width; 22 | } 23 | 24 | public function getHeight() 25 | { 26 | return $this->height; 27 | } 28 | 29 | public function calculateArea() 30 | { 31 | return $this->height * $this->width; 32 | } 33 | 34 | public abstract function resize($height, $width); 35 | } 36 | 37 | class Rectangle extends Parallelogram 38 | { 39 | public function resize($height, $width) 40 | { 41 | $this->height = $height; 42 | $this->width = $width; 43 | } 44 | } 45 | 46 | class Square extends Parallelogram { 47 | 48 | public function resize($height, $width) 49 | { 50 | $this->width = $width; 51 | $this->height = $width; 52 | } 53 | } 54 | 55 | class GraphicEditor 56 | { 57 | public function resize(Parallelogram $parallelogram) 58 | { 59 | $parallelogram->resize( 60 | $parallelogram->getHeight() * 2, 61 | $parallelogram->getWidth() * 4 62 | ); 63 | } 64 | } -------------------------------------------------------------------------------- /src/GSoares/SOLID/LiskovSubstitution/README.md: -------------------------------------------------------------------------------- 1 | Liskov Substitution Principle (LSP) 2 | ===== 3 | 4 | A definição do LSP que foi criado por Barbara Liskov, em 1988 (daí o nome), afirma 5 | que "Classes derivadas devem poder ser substituídas por suas classes base". 6 | 7 | 8 | “Se para cada objeto o1 do tipo S há um objeto o2 do tipo T de forma que, para todos os programas P definidos em 9 | termos de T, o comportamento de P é inalterado quando o1 é substituído por o2 então S é um subtipo de T” 10 | 11 | 12 | * Atender o LSP, significa que as classes derivadas são completamente substituíveis por suas classes-base, ou seja, 13 | todo o código que utilizar a classe base será capaz de atender o LSP. 14 | -------------------------------------------------------------------------------- /src/GSoares/SOLID/LiskovSubstitution/Wrong.php: -------------------------------------------------------------------------------- 1 | width = $width; 26 | } 27 | 28 | public function setHeight($height) 29 | { 30 | $this->height = $height; 31 | } 32 | 33 | public function getWidth() 34 | { 35 | return $this->width; 36 | } 37 | 38 | public function getHeight() 39 | { 40 | return $this->height; 41 | } 42 | 43 | public function calculateArea() 44 | { 45 | return $this->height * $this->width; 46 | } 47 | } 48 | 49 | class Square extends Rectangle { 50 | 51 | public function setWidth($width) 52 | { 53 | $this->width = $width; 54 | $this->height = $width; 55 | } 56 | 57 | public function setHeight($height) 58 | { 59 | $this->width = $height; 60 | $this->height = $height; 61 | } 62 | } 63 | 64 | class GraphicEditor 65 | { 66 | public function resize(Rectangle $rectangle) 67 | { 68 | $rectangle->setHeight($rectangle->getHeight() * 2); 69 | $rectangle->setWidth($rectangle->getWidth() * 4); 70 | } 71 | } -------------------------------------------------------------------------------- /src/GSoares/SOLID/OpenClosed/Correct.php: -------------------------------------------------------------------------------- 1 | turnOn(); 46 | $vehicle->run(); 47 | } 48 | } -------------------------------------------------------------------------------- /src/GSoares/SOLID/OpenClosed/README.md: -------------------------------------------------------------------------------- 1 | Open/Closed Principle (OCP) 2 | ===== 3 | 4 | A definição deste princípio OCP, que significa "Aberto e Fechado" afirma que: 5 | “Uma classe deve estar aberta para extensão, mas fechada para alteração”. 6 | 7 | Para contemplar este princípio utilizamos de abastrações e poliforfismo. Ao estender um novo comportamento em uma 8 | classe, devemos criar código novo e não alterar código existente. 9 | -------------------------------------------------------------------------------- /src/GSoares/SOLID/OpenClosed/Wrong.php: -------------------------------------------------------------------------------- 1 | turnOnMotorcycle(); 33 | } 34 | 35 | if ($vehicle instanceof Car) { 36 | $this->turnOnCar(); 37 | } 38 | 39 | $vehicle->run(); 40 | } 41 | 42 | private function turnOnCar() 43 | { 44 | echo 'Turning on the car'; 45 | } 46 | 47 | private function turnOnMotorcycle() 48 | { 49 | echo 'Turning on the motorcycle'; 50 | } 51 | } -------------------------------------------------------------------------------- /src/GSoares/SOLID/SingleResponsability/Correct.php: -------------------------------------------------------------------------------- 1 | setBalance($this->getBalance() - $value); 24 | } 25 | 26 | public function haveBalanceAvailable($value) 27 | { 28 | return $this->getBalance() >= $value; 29 | } 30 | } 31 | 32 | class Customer 33 | { 34 | public function getAccount() {} 35 | } 36 | 37 | class Sale 38 | { 39 | public function getValue() {} 40 | public function setValue() {} 41 | 42 | public function sell(array $products, Customer $customer) 43 | { 44 | $value = $this->calculateTotalValue($products); 45 | 46 | if (!$customer->getAccount()->haveBalanceAvailable($value)) { 47 | throw new NoBalanceAvailableException(); 48 | } 49 | 50 | /*..... something.....*/ 51 | 52 | $this->setValue($value); 53 | $customer->getAccount()->calculateBalance($value); 54 | } 55 | 56 | public function calculateTotalValue(array $products) 57 | { 58 | $value = 0; 59 | 60 | foreach ($products as $product) { 61 | $value += $product->getValue(); 62 | } 63 | 64 | return $value; 65 | } 66 | } -------------------------------------------------------------------------------- /src/GSoares/SOLID/SingleResponsability/README.md: -------------------------------------------------------------------------------- 1 | Single Responsability Principle (SRP) 2 | ===== 3 | 4 | A definição de LRP que significa "Única Responsabilidade" afirma que: “Uma classe deve ter somente uma razão para mudar”, ou 5 | seja, uma classe deve apenas ter uma razão de existir e não cuidar de regras que não pertencem ao escopo de sua existência, 6 | possuindo uma "responsabilidade única". -------------------------------------------------------------------------------- /src/GSoares/SOLID/SingleResponsability/Wrong.php: -------------------------------------------------------------------------------- 1 | calculateTotalValue($products); 44 | 45 | if (!$this->haveBalanceAvailable($customer, $value)) { 46 | throw new NoBalanceAvailableException(); 47 | } 48 | 49 | /*..... something.....*/ 50 | 51 | $this->setValue($value); 52 | $this->calculateBalance($customer); 53 | } 54 | 55 | public function calculateBalance(Customer $customer) 56 | { 57 | $customer->getAccount()->setBalance($customer->getAccount()->getBalance() - $this->getValue()); 58 | } 59 | 60 | public function haveBalanceAvailable(Customer $customer, $value) 61 | { 62 | return $customer->getAccount()->getBalance() >= $value; 63 | } 64 | 65 | private function calculateTotalValue(array $products) 66 | { 67 | $value = 0; 68 | 69 | foreach ($products as $product) { 70 | $value += $product->getValue(); 71 | } 72 | 73 | return $value; 74 | } 75 | } --------------------------------------------------------------------------------