├── Procfile ├── README.md ├── UC-01a02f43-a465-4d80-9d6b-904360fa9ec9.jpg ├── background.png ├── basic-projects-db.sql ├── deploy.sh ├── images ├── heranca.png └── heranca2.png ├── index.php └── projects-php ├── php-chat ├── README.md ├── assets │ ├── css │ │ └── main.css │ ├── js │ │ └── main.js │ └── sounds │ │ └── chat.mp3 ├── controller │ └── chat.php ├── index.php └── model │ ├── chat.sql │ └── db.php ├── php-crud ├── css │ └── style.css ├── db.php ├── db.sql ├── deleta_aluno.php ├── deleta_curso.php ├── edita_curso.php ├── footer.php ├── header.php ├── img │ ├── 300x300.png │ └── crud_logo.png ├── index.php ├── login.php ├── logout.php ├── processa_aluno.php ├── processa_curso.php ├── processa_matricula.php └── views │ ├── alunos.php │ ├── cursos.php │ ├── home.php │ ├── inserir_matriculas.php │ ├── inserir_novo_aluno.php │ ├── inserir_novo_curso.php │ └── matriculas.php ├── php-design-patterns-cadastro-solid ├── Dockerfile ├── app │ ├── .gitignore │ ├── composer.json │ ├── composer.lock │ ├── index.php │ └── src │ │ ├── Bolo.php │ │ ├── Entrega.php │ │ └── Pedido.php ├── docker-compose.yml └── readme.md ├── php-design-patterns ├── .gitignore ├── Behavorial │ ├── Iterator.php │ ├── PubSub.php │ ├── Strategy.php │ └── Visitor.php ├── Concurrency │ └── readme.md ├── Creational │ ├── Builder.php │ ├── Factory.php │ └── Singleton.php ├── Dockerfile ├── InversionControl │ ├── DependencyInjection.php │ └── ServiceLocator.php ├── Structural │ ├── Adapter.php │ ├── Decorator.php │ ├── Flyweight.php │ └── Proxy.php ├── certificate.PNG ├── docker-compose.yml ├── readme.md ├── src │ ├── DependencyInversion.php │ ├── DependencyInversion2.php │ ├── InterfaceSegragation.php │ ├── InterfaceSegragation2.php │ ├── LiskovSubstitution.php │ ├── LiskovSubstitution2.php │ ├── OpenClose.php │ ├── OpenClose2.php │ ├── SingleResposability.php │ └── index.php └── summary.png ├── php-form ├── README.md ├── images │ └── php-logo.svg ├── index.php ├── script.php └── servicos │ ├── defineNome.php │ ├── servicoMensagemSessao.php │ └── servicoValidacao.php ├── php-nif-validation ├── Dockerfile ├── README.md ├── docker-compose.yml └── src │ ├── index.php │ └── service │ ├── NIFValidationService.php │ └── NIFValidationServiceInterface.php ├── php-oo-2 ├── challenge-date │ └── challenge-date.png ├── challenge-excecoes │ └── challenge-excecoes.png ├── challenge-pdo-blog-final │ └── exercicio-final-oo.PNG ├── challenge-vendas │ ├── challenge-vendas.png │ ├── index.php │ └── vendas.class.php ├── exercicio-banco │ ├── ContaBancaria.class.php │ └── index.php ├── exercicio-date │ └── index.php ├── exercicio-excecoes │ ├── index.php │ ├── validarUsuarioComExcecao.php │ ├── validarUsuarioComTryCatch.php │ └── validarUsuarioSemExcecao.php ├── exercicio-pdo │ ├── index.php │ └── src │ │ ├── Produtos.class.php │ │ └── old │ │ ├── connect.php │ │ ├── deleteDB.php │ │ ├── insertDB.php │ │ ├── listDB.php │ │ └── updateDB.php ├── index.php ├── oo-old │ ├── Pessoa.php │ ├── Programador.php │ ├── conecta.php │ ├── conecta2.php │ └── index.php └── readme.md ├── php-oo ├── index.php ├── page0.php ├── page1.php ├── page2.php ├── page3.php ├── page4.php ├── page5.php ├── page6.php ├── page7.php └── page8.php ├── php-search ├── .gitignore ├── README.md ├── controller │ ├── InsertController.php │ └── SearchController.php ├── index.php ├── model │ └── db.php └── view │ ├── assets │ ├── css │ │ └── main.css │ └── js │ │ └── main.js │ └── front │ ├── footer.php │ ├── header.php │ ├── home.php │ ├── insert.php │ └── results.php ├── php-swoole ├── docker-compose.yml ├── index.html └── server.php ├── php-tips ├── .gitignore ├── README.md ├── api │ └── index.php ├── docker-compose.yaml ├── index.html ├── tip1 │ └── generator.php ├── tip2 │ └── fibers.php ├── tip3 │ └── attributes.php ├── tip4 │ └── types.php ├── tip5 │ ├── .env │ ├── .gitignore │ ├── bin │ │ └── console │ ├── composer.json │ ├── composer.lock │ ├── config │ │ ├── bundles.php │ │ ├── packages │ │ │ ├── cache.yaml │ │ │ ├── framework.yaml │ │ │ └── routing.yaml │ │ ├── preload.php │ │ ├── routes.yaml │ │ ├── routes │ │ │ └── framework.yaml │ │ └── services.yaml │ ├── public │ │ └── index.php │ ├── src │ │ ├── Controller │ │ │ └── .gitignore │ │ ├── Kernel.php │ │ └── Maker │ │ │ ├── MakeNewClass.php │ │ │ ├── NewClass.php │ │ │ ├── NewClass.tpl.php │ │ │ └── NewClass.txt │ └── symfony.lock ├── tip7 │ ├── index.php │ └── post.md └── vercel.json ├── php-todo ├── README.md ├── assets │ ├── css │ │ ├── bootstrap-grid.css │ │ ├── bootstrap-grid.css.map │ │ ├── bootstrap-grid.min.css │ │ ├── bootstrap-grid.min.css.map │ │ ├── bootstrap-reboot.css │ │ ├── bootstrap-reboot.css.map │ │ ├── bootstrap-reboot.min.css │ │ ├── bootstrap-reboot.min.css.map │ │ ├── bootstrap.css │ │ ├── bootstrap.css.map │ │ ├── bootstrap.min.css │ │ └── bootstrap.min.css.map │ ├── images │ │ └── fav │ │ │ ├── android-icon-144x144.png │ │ │ ├── android-icon-192x192.png │ │ │ ├── android-icon-36x36.png │ │ │ ├── android-icon-48x48.png │ │ │ ├── android-icon-72x72.png │ │ │ ├── android-icon-96x96.png │ │ │ ├── apple-icon-114x114.png │ │ │ ├── apple-icon-120x120.png │ │ │ ├── apple-icon-144x144.png │ │ │ ├── apple-icon-152x152.png │ │ │ ├── apple-icon-180x180.png │ │ │ ├── apple-icon-57x57.png │ │ │ ├── apple-icon-60x60.png │ │ │ ├── apple-icon-72x72.png │ │ │ ├── apple-icon-76x76.png │ │ │ ├── apple-icon-precomposed.png │ │ │ ├── apple-icon.png │ │ │ ├── browserconfig.xml │ │ │ ├── favicon-16x16.png │ │ │ ├── favicon-32x32.png │ │ │ ├── favicon-96x96.png │ │ │ ├── favicon.ico │ │ │ ├── manifest.json │ │ │ ├── ms-icon-144x144.png │ │ │ ├── ms-icon-150x150.png │ │ │ ├── ms-icon-310x310.png │ │ │ └── ms-icon-70x70.png │ ├── js │ │ ├── bootstrap.bundle.js │ │ ├── bootstrap.bundle.js.map │ │ ├── bootstrap.bundle.min.js │ │ ├── bootstrap.bundle.min.js.map │ │ ├── bootstrap.js │ │ ├── bootstrap.js.map │ │ ├── bootstrap.min.js │ │ └── bootstrap.min.js.map │ └── sql │ │ ├── database.sql │ │ └── queries.php ├── index.php ├── model │ ├── apagar_anotacao.php │ ├── atualizar_anotacao.php │ ├── database.php │ └── inserir_anotacao.php └── views │ ├── .gitattributes │ ├── atualizar.php │ ├── footer.php │ ├── header.php │ ├── home.php │ └── inserir.php ├── php-unit-tests ├── .vscode │ └── launch.json ├── Dockerfile ├── README.md ├── app │ ├── .gitignore │ ├── composer.json │ ├── composer.lock │ ├── phpunit.xml │ ├── src │ │ ├── CalculatorService.php │ │ ├── Formatter.php │ │ ├── ItemsTable.php │ │ ├── PrintCalculationService.php │ │ ├── Receipt.php │ │ └── index.php │ └── tests │ │ ├── CalculatorServiceTest.php │ │ ├── FormatterTest.php │ │ ├── ItemsTableTest.php │ │ └── ReceiptTest.php ├── certificate-debug.png ├── certificate.png ├── debugs.md ├── docker-compose.yml └── testes.png └── php-zend-certification ├── .gitignore ├── Behavorial ├── Flyweight.php ├── Iterator.php ├── PubSub.php ├── Strategy.php └── Visitor.php ├── Concurrency └── readme.md ├── Creational ├── Builder.php └── Factory.php ├── InversionControl ├── DependencyInjection.php └── ServiceLocator.php ├── Structural ├── Adapter.php ├── Decorator.php └── Proxy.php ├── certificate.png ├── readme.md └── summary.png /Procfile: -------------------------------------------------------------------------------- 1 | web: heroku-php-apache2 / -------------------------------------------------------------------------------- /UC-01a02f43-a465-4d80-9d6b-904360fa9ec9.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RazielRodrigues/php-projects/551e08b0b6aafea510a004dab9268b88c1b627f7/UC-01a02f43-a465-4d80-9d6b-904360fa9ec9.jpg -------------------------------------------------------------------------------- /background.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RazielRodrigues/php-projects/551e08b0b6aafea510a004dab9268b88c1b627f7/background.png -------------------------------------------------------------------------------- /deploy.sh: -------------------------------------------------------------------------------- 1 | git add . 2 | git commit -am "deploy" 3 | git push heroku master 4 | git push heroku main 5 | 6 | # mysql://bfff28e7229e4b:bef6c00e@us-cdbr-east-05.cleardb.net/heroku_201a8405690d62f?reconnect=true -------------------------------------------------------------------------------- /images/heranca.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RazielRodrigues/php-projects/551e08b0b6aafea510a004dab9268b88c1b627f7/images/heranca.png -------------------------------------------------------------------------------- /images/heranca2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RazielRodrigues/php-projects/551e08b0b6aafea510a004dab9268b88c1b627f7/images/heranca2.png -------------------------------------------------------------------------------- /projects-php/php-chat/README.md: -------------------------------------------------------------------------------- 1 | # PHP AJAX CHAT SYSTEM 2 | 3 | In this mini project I gonna build a mini chat system with PHP and AJAX: 4 | 5 | https://www.udemy.com/course/draft/692878/learn/lecture/4145360#overview 6 | 7 |

This is a simple chat project which use PHP and AJAX to do the chat.

-------------------------------------------------------------------------------- /projects-php/php-chat/assets/css/main.css: -------------------------------------------------------------------------------- 1 | *{ 2 | padding: 0; 3 | margin: 0; 4 | border: 0; 5 | } 6 | 7 | body{ 8 | background-color: whitesmoke; 9 | } 10 | 11 | #container{ 12 | width: 40%; 13 | background-color: white; 14 | margin: 0 auto; 15 | padding: 20px; 16 | } 17 | 18 | #chat-box{ 19 | width: 90%; 20 | height: 400px; 21 | } 22 | 23 | #chat-data{ 24 | width: 100%; 25 | padding: 5px; 26 | margin-bottom: 5px; 27 | border: 1px solid silver; 28 | } 29 | 30 | input[type='text']{ 31 | width: 100%; 32 | height: 40px; 33 | border: 1px solid gray; 34 | border-radius: 5px 35 | } 36 | 37 | input[type='submit']{ 38 | width: 100%; 39 | height: 40px; 40 | border: 1px solid gray; 41 | border-radius: 5px 42 | } 43 | 44 | textarea{ 45 | width: 100%; 46 | height: 40px; 47 | border: 1px solid gray; 48 | border-radius: 5px 49 | } -------------------------------------------------------------------------------- /projects-php/php-chat/assets/js/main.js: -------------------------------------------------------------------------------- 1 | function getChat() { 2 | var getChat = new XMLHttpRequest(); 3 | getChat.onreadystatechange = function () { 4 | if (this.readyState == 4 && this.status == 200) { 5 | document.getElementById("chat").innerHTML = this.responseText; 6 | } 7 | }; 8 | getChat.open("GET", "controller/chat.php", true); 9 | getChat.send(); 10 | } 11 | setInterval(() => {getChat()}, 1000); 12 | -------------------------------------------------------------------------------- /projects-php/php-chat/assets/sounds/chat.mp3: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RazielRodrigues/php-projects/551e08b0b6aafea510a004dab9268b88c1b627f7/projects-php/php-chat/assets/sounds/chat.mp3 -------------------------------------------------------------------------------- /projects-php/php-chat/controller/chat.php: -------------------------------------------------------------------------------- 1 | query($query)->fetchAll(); 7 | foreach ($chatSelect as $data) { 8 | ?> 9 |
10 | : 11 | 12 | 13 | 14 |
15 | 16 | query($chatInsert); 22 | if ($insertMessage) { 23 | echo ""; 24 | header('location: ../index.php'); 25 | } 26 | } 27 | ?> -------------------------------------------------------------------------------- /projects-php/php-chat/index.php: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | PHP AJAX CHAT SYSTEM 7 | 8 | 9 | 10 | 11 |
12 |
13 |

GLOBAL AJAX CHAT

14 |
15 |
16 |
17 |
18 | Loading messages... 19 |
20 |
21 | 22 |
23 | 24 | 25 | 26 |
27 | 28 |
29 | 30 | -------------------------------------------------------------------------------- /projects-php/php-chat/model/chat.sql: -------------------------------------------------------------------------------- 1 | -- TODO: MOVE TO DB CLASS 2 | CREATE TABLE CHAT( 3 | ID INT PRIMARY KEY AUTO_INCREMENT, 4 | NAME VARCHAR(255) NOT NULL, 5 | MESSAGE VARCHAR(255) NOT NULL, 6 | DATE TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP 7 | ); -------------------------------------------------------------------------------- /projects-php/php-chat/model/db.php: -------------------------------------------------------------------------------- 1 | setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 11 | } catch(PDOException $e) { 12 | echo "Connection failed: " . $e->getMessage(); 13 | } -------------------------------------------------------------------------------- /projects-php/php-crud/css/style.css: -------------------------------------------------------------------------------- 1 | body{ 2 | font-family: 'Source Code Pro', monospace; 3 | font-size: 20px; 4 | background-color: white; 5 | 6 | } 7 | 8 | header{ 9 | height: 120px; 10 | background-color: whitesmoke; 11 | color: black; 12 | } 13 | 14 | 15 | footer{ 16 | background-color: whitesmoke; 17 | color: black; 18 | text-align: center; 19 | padding: 30px; 20 | } 21 | 22 | .container{ 23 | margin: auto; width: auto; 24 | } 25 | 26 | #conteudo{ 27 | background-color: white; 28 | padding: 140px; 29 | text-align: left; 30 | } 31 | 32 | #menu{ 33 | float: right; 34 | text-decoration: none; 35 | margin-top: 2.5rem; 36 | padding-right: 10rem; 37 | } 38 | 39 | #menu a{ 40 | text-decoration: none; 41 | padding: 2rem; 42 | 43 | } 44 | 45 | #menu a:hover{ 46 | background-color: white; 47 | border-radius: 100px; 48 | } -------------------------------------------------------------------------------- /projects-php/php-crud/db.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /projects-php/php-crud/deleta_curso.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /projects-php/php-crud/edita_curso.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /projects-php/php-crud/footer.php: -------------------------------------------------------------------------------- 1 | 2 | 3 | 26 | 27 | -------------------------------------------------------------------------------- /projects-php/php-crud/header.php: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | C.R.U.D COM PHP e MySQL | RAZIEL M. 10 | 11 | 12 | 13 | 51 | 52 |
-------------------------------------------------------------------------------- /projects-php/php-crud/img/300x300.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RazielRodrigues/php-projects/551e08b0b6aafea510a004dab9268b88c1b627f7/projects-php/php-crud/img/300x300.png -------------------------------------------------------------------------------- /projects-php/php-crud/img/crud_logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RazielRodrigues/php-projects/551e08b0b6aafea510a004dab9268b88c1b627f7/projects-php/php-crud/img/crud_logo.png -------------------------------------------------------------------------------- /projects-php/php-crud/index.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /projects-php/php-crud/login.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /projects-php/php-crud/logout.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /projects-php/php-crud/processa_aluno.php: -------------------------------------------------------------------------------- 1 | 2 | inserir novo aluno 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | '; 19 | echo "'; 20 | ?> 21 | 22 | 23 | 24 | 25 | 26 | 31 | 32 |
Nome aluno:Data nascimento:DeletarEditar
".$linha['NOME_ALUNOS'].'".$linha['DATA_NASCIMENTO'].'Deletar
33 | -------------------------------------------------------------------------------- /projects-php/php-crud/views/cursos.php: -------------------------------------------------------------------------------- 1 |
2 | inserir novo curso 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | '; 18 | echo "'; 19 | 20 | ?> 21 | 22 | 23 | 24 | 25 | 26 | 27 | 32 | 33 |
Nome cursoCarga horariaDeletarEditar
".$linha['NOME_CURSOS'].'".$linha['CARGA_HORARIA'].'EditarDeletar
34 |
-------------------------------------------------------------------------------- /projects-php/php-crud/views/home.php: -------------------------------------------------------------------------------- 1 | 4 | Usuario ou senha invalido
'; 5 | } 6 | 7 | ?> 8 | 9 | 10 |
11 |
12 |

Bem vindo ao C.R.U.D

13 |
14 | 15 | 16 | 17 |
18 |
19 |
-------------------------------------------------------------------------------- /projects-php/php-crud/views/inserir_matriculas.php: -------------------------------------------------------------------------------- 1 |

inserir matriculas

2 | 3 |
4 | 5 | 12 | 13 | 14 | 21 | 22 |

23 | 24 | 25 | 26 |
-------------------------------------------------------------------------------- /projects-php/php-crud/views/inserir_novo_aluno.php: -------------------------------------------------------------------------------- 1 |

Inserir novo aluno

2 |
3 | 4 |
5 | 6 |
7 | 8 |
-------------------------------------------------------------------------------- /projects-php/php-crud/views/inserir_novo_curso.php: -------------------------------------------------------------------------------- 1 | 2 | 3 |

Inserir novo curso

4 |
5 | 6 |
7 | 8 |
9 | 10 |
11 | 12 | 13 | 14 | 15 | 16 | 17 |

Editar curso

18 |
19 |
20 | 21 | 22 |
23 | 24 |
25 | 26 |
27 | 28 | 29 | 30 | 31 | -------------------------------------------------------------------------------- /projects-php/php-crud/views/matriculas.php: -------------------------------------------------------------------------------- 1 |
2 | inserir matricula 3 |

EM CONSTRUÇÃO

4 |
5 | -------------------------------------------------------------------------------- /projects-php/php-design-patterns-cadastro-solid/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM php:7.2-apache 2 | RUN docker-php-ext-install mysqli 3 | RUN curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/local/bin --filename=composer -------------------------------------------------------------------------------- /projects-php/php-design-patterns-cadastro-solid/app/.gitignore: -------------------------------------------------------------------------------- 1 | vendor -------------------------------------------------------------------------------- /projects-php/php-design-patterns-cadastro-solid/app/composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "root/html", 3 | "autoload": { 4 | "psr-4": { 5 | "Bolos\\": "src/" 6 | } 7 | }, 8 | "authors": [ 9 | { 10 | "name": "Raziel Rodrigues" 11 | } 12 | ], 13 | "require": {} 14 | } 15 | -------------------------------------------------------------------------------- /projects-php/php-design-patterns-cadastro-solid/app/composer.lock: -------------------------------------------------------------------------------- 1 | { 2 | "_readme": [ 3 | "This file locks the dependencies of your project to a known state", 4 | "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", 5 | "This file is @generated automatically" 6 | ], 7 | "content-hash": "7bda50acfaac41a19518426a66bcd020", 8 | "packages": [], 9 | "packages-dev": [], 10 | "aliases": [], 11 | "minimum-stability": "stable", 12 | "stability-flags": [], 13 | "prefer-stable": false, 14 | "prefer-lowest": false, 15 | "platform": [], 16 | "platform-dev": [], 17 | "plugin-api-version": "2.3.0" 18 | } 19 | -------------------------------------------------------------------------------- /projects-php/php-design-patterns-cadastro-solid/app/index.php: -------------------------------------------------------------------------------- 1 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | FABRICA DE BOLOS SOLID PHP 17 | 18 | 19 | 20 | 21 |
22 |

Fabrica de bolos SOLID PHP

23 |
24 | 28 |
29 | 33 |
34 | 35 |
36 | 37 | preparar(); 46 | $pedido->entregar(); 47 | } 48 | 49 | ?> 50 | 51 | 52 | 53 | 54 | -------------------------------------------------------------------------------- /projects-php/php-design-patterns-cadastro-solid/app/src/Bolo.php: -------------------------------------------------------------------------------- 1 | assar'; 24 | } 25 | public function misturar() 26 | { 27 | echo '

misturar

'; 28 | } 29 | public function servir() 30 | { 31 | echo '

servir normal

'; 32 | } 33 | } 34 | 35 | class BoloCenoura extends Bolo implements BoloCenouraInterface 36 | { 37 | public function assar() 38 | { 39 | echo '

assar 45 minutos

'; 40 | } 41 | public function misturar() 42 | { 43 | echo '

misturar 10 minutos

'; 44 | } 45 | public function cobertura() 46 | { 47 | echo '

cobertura 10 gramas

'; 48 | } 49 | } 50 | 51 | class BoloChocolate extends Bolo implements BoloChocolateInterface 52 | { 53 | public function assar() 54 | { 55 | echo '

assar 34 minutos

'; 56 | } 57 | public function misturar() 58 | { 59 | echo '

misturar 2 minutos

'; 60 | } 61 | public function calda() 62 | { 63 | echo '

calda 200 ml

'; 64 | } 65 | public function servir() 66 | { 67 | echo '

servir no prato

'; 68 | } 69 | } -------------------------------------------------------------------------------- /projects-php/php-design-patterns-cadastro-solid/app/src/Entrega.php: -------------------------------------------------------------------------------- 1 | São Paulo'; 23 | } 24 | public function status(){ 25 | echo '

indo até você

'; 26 | } 27 | public function horas(){ 28 | echo '

4 horas...

'; 29 | } 30 | } 31 | 32 | class EntregaMoto implements EntregaMotoInterface 33 | { 34 | public function localizacao(){ 35 | echo '

marydota

'; 36 | } 37 | public function status(){ 38 | echo '

indo até você

'; 39 | } 40 | public function minutos(){ 41 | echo '

15 minutos...

'; 42 | } 43 | } -------------------------------------------------------------------------------- /projects-php/php-design-patterns-cadastro-solid/app/src/Pedido.php: -------------------------------------------------------------------------------- 1 | entrega = $entrega; 15 | $this->bolo = $bolo; 16 | } 17 | 18 | public function preparar(){ 19 | $this->bolo->assar(); 20 | $this->bolo->misturar(); 21 | } 22 | 23 | public function entregar(){ 24 | $this->entrega->localizacao(); 25 | $this->entrega->status(); 26 | } 27 | 28 | } -------------------------------------------------------------------------------- /projects-php/php-design-patterns-cadastro-solid/docker-compose.yml: -------------------------------------------------------------------------------- 1 | php: 2 | build: . 3 | ports: 4 | - "80:80" 5 | volumes: 6 | - ./app:/var/www/html -------------------------------------------------------------------------------- /projects-php/php-design-patterns-cadastro-solid/readme.md: -------------------------------------------------------------------------------- 1 | ### TREINO SOLID 2 | 3 | Single - Somente uma responsabilidade 4 | 5 | Open closed - Derivar de interfaces e não de classes (polimorfismo) 6 | 7 | Liskov - Não usar override de metodo atoa 8 | 9 | Interface - Abstrair ao maximo as interfaces 10 | 11 | Dependency - Não ficar dando $x = new Objeto() dentro de classes, invez disso usar Injeção com interfaces -------------------------------------------------------------------------------- /projects-php/php-design-patterns/.gitignore: -------------------------------------------------------------------------------- 1 | /zend 2 | /php_oop_student_files -------------------------------------------------------------------------------- /projects-php/php-design-patterns/Behavorial/Iterator.php: -------------------------------------------------------------------------------- 1 | $content]); 16 | } 17 | } 18 | 19 | class FormatArray implements FormatStategy 20 | { 21 | public function render(mixed $content): string 22 | { 23 | return print_r([$content => $content], true); 24 | } 25 | } 26 | 27 | # Using polymorphism 28 | class FormatPolymorphism 29 | { 30 | 31 | public function format(string $content, FormatStategy $format): void 32 | { 33 | echo $format->render($content); 34 | } 35 | } 36 | 37 | (new FormatPolymorphism())->format('Raziel...', new FormatArray()); 38 | (new FormatPolymorphism())->format('Raziel...', new FormatJson); 39 | 40 | # Delegating for a structure of control 41 | class FormatDelegating 42 | { 43 | 44 | public function format(string $content, string $format): void 45 | { 46 | echo match ($format) { 47 | 'json' => (new FormatJson)->render($content), 48 | 'array' => (new FormatArray)->render($content), 49 | }; 50 | } 51 | } 52 | 53 | (new FormatDelegating())->format('Raziel...', 'json'); 54 | (new FormatDelegating())->format('Raziel...', 'array'); 55 | -------------------------------------------------------------------------------- /projects-php/php-design-patterns/Behavorial/Visitor.php: -------------------------------------------------------------------------------- 1 | id = $id; 14 | return $this; 15 | } 16 | 17 | 18 | public function setFirstName(string $firstName): UserBuilder 19 | { 20 | $this->firstName = $firstName; 21 | return $this; 22 | } 23 | 24 | public function build(): array 25 | { 26 | return array( 27 | 'id' => $this->id, 28 | 'first_name' => $this->firstName 29 | ); 30 | } 31 | } 32 | 33 | # $user = new UserBuilder; 34 | # $user->setId(1); 35 | # $user->setFirstName('Raziel Rodrigues'); 36 | # print_r($user->build()); -------------------------------------------------------------------------------- /projects-php/php-design-patterns/Creational/Factory.php: -------------------------------------------------------------------------------- 1 | id = $id; 15 | return $this; 16 | } 17 | 18 | 19 | public function getId(): int 20 | { 21 | return $this->id; 22 | } 23 | 24 | 25 | public function setFirstName(string $firstName): User 26 | { 27 | $this->firstName = $firstName; 28 | return $this; 29 | } 30 | 31 | public function getFirstName(): string 32 | { 33 | return $this->firstName; 34 | } 35 | } 36 | 37 | 38 | class UserFactory 39 | { 40 | 41 | public function __construct( 42 | private int $id, 43 | private string $firstName 44 | ) { 45 | } 46 | 47 | public function create(): User 48 | { 49 | return (new User()) 50 | ->setId($this->id) 51 | ->setFirstName(strtolower($this->firstName)); 52 | } 53 | } 54 | 55 | $user1 = (new UserFactory(time(), 'JhOn Cena'))->create(); 56 | echo 'ID - ' . $user1->getId() . 'NAME - ' . $user1->getFirstName() . PHP_EOL; 57 | 58 | $user2 = (new UserFactory(time(), 'UNDERTAKER'))->create(); 59 | echo 'ID - ' . $user2->getId() . 'NAME - ' . $user2->getFirstName() . PHP_EOL; 60 | 61 | echo '### OTHER IMPLEMENTATION FACTORY PATTERN ### ' . PHP_EOL; 62 | 63 | interface CarFactory 64 | { 65 | public function create(): Car; 66 | } 67 | 68 | interface Car 69 | { 70 | public function getType(): string; 71 | } 72 | 73 | class SedanFactory implements CarFactory 74 | { 75 | public function create(): Car 76 | { 77 | return new Sedan(); 78 | } 79 | } 80 | 81 | class Sedan implements Car 82 | { 83 | public function getType(): string 84 | { 85 | return 'Sedan'; 86 | } 87 | } 88 | 89 | $car = (new SedanFactory())->create(); 90 | echo 'TYPE - ' . $car->getType() . PHP_EOL; 91 | -------------------------------------------------------------------------------- /projects-php/php-design-patterns/Creational/Singleton.php: -------------------------------------------------------------------------------- 1 | lightStatus = 'OFF'; 9 | } 10 | 11 | public static function getInstance(): LuzSingleton { 12 | if (self::$instance === null) { 13 | self::$instance = new self(); 14 | } 15 | return self::$instance; 16 | } 17 | 18 | /** 19 | * Turns the light ON. 20 | */ 21 | public function turnOn(): void { 22 | $this->lightStatus = 'ON'; 23 | echo "Light turned {$this->lightStatus}\n"; 24 | } 25 | 26 | /** 27 | * Turns the light OFF. 28 | */ 29 | public function turnOff(): void { 30 | $this->lightStatus = 'OFF'; 31 | echo "Light turned {$this->lightStatus}\n"; 32 | } 33 | 34 | /** 35 | * Retrieves the current status of the light. 36 | * 37 | * @return string The current light status. 38 | */ 39 | public function getStatus(): string { 40 | return $this->lightStatus; 41 | } 42 | } 43 | 44 | // Exemplo de uso 45 | $luz = LuzSingleton::getInstance(); 46 | $luz->turnOn(); 47 | echo $luz->getStatus(); // ON 48 | 49 | -------------------------------------------------------------------------------- /projects-php/php-design-patterns/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM php:7.2-apache 2 | RUN docker-php-ext-install mysqli -------------------------------------------------------------------------------- /projects-php/php-design-patterns/InversionControl/DependencyInjection.php: -------------------------------------------------------------------------------- 1 | calculate(2, 3); 33 | } 34 | } 35 | 36 | class DependecyInjection 37 | { 38 | 39 | public function __construct(public Calculation $sum) 40 | { 41 | } 42 | 43 | public function get() 44 | { 45 | return $this->sum->calculate(2, 3); 46 | } 47 | } 48 | 49 | 50 | echo (new NoDependecyInjection())->get() . PHP_EOL; 51 | 52 | echo (new DependecyInjection(new Sum))->get() . PHP_EOL; 53 | 54 | echo (new DependecyInjection(new Minus))->get() . PHP_EOL; 55 | -------------------------------------------------------------------------------- /projects-php/php-design-patterns/InversionControl/ServiceLocator.php: -------------------------------------------------------------------------------- 1 | new Sum(), 27 | 'minus' => new Minus(), 28 | }; 29 | } 30 | } 31 | 32 | class Main 33 | { 34 | 35 | public function __construct(public ServiceLocator $serviceLocator) 36 | { 37 | } 38 | 39 | public function run($name) 40 | { 41 | $service = $this->serviceLocator->get($name); 42 | return $service->calculate(10, 2); 43 | } 44 | } 45 | 46 | 47 | echo (new Main(new ServiceLocator))->run('sum') . PHP_EOL; 48 | echo (new Main(new ServiceLocator))->run('minus') . PHP_EOL; 49 | -------------------------------------------------------------------------------- /projects-php/php-design-patterns/Structural/Adapter.php: -------------------------------------------------------------------------------- 1 | emailService = $emailService; 37 | } 38 | 39 | 40 | public function send(string $to, string $subject, string $body): string 41 | { 42 | return $this->emailService->send($to, $subject, $body); 43 | } 44 | } 45 | 46 | $adapater = new EmailServiceAdapter(new GoogleEmailService()); 47 | $adapter2 = new EmailServiceAdapter(new MicrosoftEmailService()); 48 | 49 | # echo $adapater->send('a@a.com', 'subject', 'body'); 50 | # echo $adapter2->send('a@a.com', 'subject', 'body'); 51 | -------------------------------------------------------------------------------- /projects-php/php-design-patterns/Structural/Decorator.php: -------------------------------------------------------------------------------- 1 | ninja->superpower()} + {$this->power}"; 58 | } 59 | } 60 | 61 | foreach ([ 62 | new NinjaKonoha, 63 | new NinjaKonoha, 64 | new NinjaSand, 65 | new NinjaSand, 66 | new NinjaStorm, 67 | new NinjaStone 68 | ] as $key => $value) { 69 | # echo PHP_EOL; 70 | # echo (new NinjaAddPowerDecorator($value, 'fire jutsu!'))->superpower() . ' new behavior :o'; 71 | } 72 | 73 | class NinjaSandExtraPower extends NinjaSand 74 | { 75 | 76 | public function __construct( 77 | private string $power = '' 78 | ) { 79 | } 80 | 81 | public function extra(): string 82 | { 83 | return parent::superpower() . " + {$this->power}"; 84 | } 85 | } 86 | 87 | class NinjaKonohaExtraPower extends NinjaKonoha 88 | { 89 | 90 | public function __construct( 91 | private string $power = '' 92 | ) { 93 | } 94 | 95 | public function extra(): string 96 | { 97 | return parent::superpower() . " + {$this->power}"; 98 | } 99 | } 100 | 101 | class NinjaStormExtraPower extends NinjaStorm 102 | { 103 | 104 | public function __construct( 105 | private string $power = '' 106 | ) { 107 | } 108 | 109 | public function extra(): string 110 | { 111 | return parent::superpower() . " + {$this->power}"; 112 | } 113 | } 114 | 115 | class NinjaStoneExtraPower extends NinjaStone 116 | { 117 | 118 | public function __construct( 119 | private string $power = '' 120 | ) { 121 | } 122 | 123 | public function extra(): string 124 | { 125 | return parent::superpower() . " + {$this->power}"; 126 | } 127 | } 128 | 129 | foreach ([ 130 | new NinjaKonohaExtraPower('fire jutsu!'), 131 | new NinjaKonohaExtraPower('fire jutsu!'), 132 | new NinjaSandExtraPower('sand jutsu!'), 133 | new NinjaSandExtraPower('sand jutsu!'), 134 | new NinjaStormExtraPower('storm jutsu!'), 135 | new NinjaStoneExtraPower('stone jutsu!') 136 | ] as $key => $value) { 137 | # echo PHP_EOL; 138 | # echo $value->extra() . ' new behavior :o'; 139 | } 140 | -------------------------------------------------------------------------------- /projects-php/php-design-patterns/Structural/Flyweight.php: -------------------------------------------------------------------------------- 1 | flyweight[$tag])) { 20 | $this->flyweight[$tag] = new Storage($tag); 21 | 22 | return $this->flyweight[$tag]; 23 | } 24 | 25 | return $this->flyweight[$tag]; 26 | } 27 | } 28 | 29 | $factory = new StorageFlyweightFactory(); 30 | 31 | echo $factory->create('Raziel')->tag; 32 | echo $factory->create('Jaiara')->tag; 33 | echo $factory->create('Lisa')->tag; 34 | echo $factory->create('Sergio')->tag; 35 | 36 | echo $factory->create('Raziel')->tag; 37 | echo $factory->create('Jaiara')->tag; 38 | echo $factory->create('Lisa')->tag; 39 | echo $factory->create('Sergio')->tag; 40 | 41 | # Three objects, but called six times! 42 | var_dump($factory->flyweight); 43 | 44 | # Difference is minimal this scenario, but imagine with big objects! 45 | echo memory_get_peak_usage(); 46 | -------------------------------------------------------------------------------- /projects-php/php-design-patterns/Structural/Proxy.php: -------------------------------------------------------------------------------- 1 | $value) { 26 | echo PHP_EOL; 27 | 28 | /** @var NinjaInterface $ninja */ 29 | $ninja = (new NinjaPowerProxy($value, rand(1, 6))); 30 | echo $ninja()->superpower(); 31 | } 32 | 33 | class NinjaPowerProxy 34 | { 35 | 36 | public function __construct( 37 | private NinjaInterface $ninja, 38 | private string $password 39 | ) { 40 | } 41 | 42 | public function __invoke() 43 | { 44 | if (empty($this->password)) { 45 | throw new ErrorException('Password needs to be filled!', 403); 46 | } 47 | 48 | if ($this->password % 2 === 0) { 49 | return new NinjaAddPowerDecorator($this->ninja, 'special jutsu!'); 50 | } 51 | 52 | return new NinjaAddPowerDecorator($this->ninja, 'normal jutsu!'); 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /projects-php/php-design-patterns/certificate.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RazielRodrigues/php-projects/551e08b0b6aafea510a004dab9268b88c1b627f7/projects-php/php-design-patterns/certificate.PNG -------------------------------------------------------------------------------- /projects-php/php-design-patterns/docker-compose.yml: -------------------------------------------------------------------------------- 1 | php: 2 | build: . 3 | ports: 4 | - "80:80" 5 | volumes: 6 | - ./src:/var/www/html -------------------------------------------------------------------------------- /projects-php/php-design-patterns/readme.md: -------------------------------------------------------------------------------- 1 | # PHP Objects: Object Oriented Programming Software Patterns 2 | 3 | This repository is about my study from the course provided by ZEND, the company behind the PHP runtime 4 | in this course I have learned about the most used patterns of PHP which includes: 5 | 6 | 7 | 8 | I also have written articles about it on my dev.to profile 9 | 10 | The course is for free and you can also enroll clicking here 12 | 13 | Plus you get a nice certificate like this one :) 14 | 15 | 16 | 17 | https://github.com/RazielRodrigues/php-projects/tree/zend-certification -------------------------------------------------------------------------------- /projects-php/php-design-patterns/src/DependencyInversion.php: -------------------------------------------------------------------------------- 1 | 2 | dbConnection = new MySQLConnection(); 13 | } 14 | 15 | // Faz alguma coisa 16 | } 17 | 18 | 19 | // use MySQLConnection; 20 | 21 | // class PasswordReminder 22 | // { 23 | // private $dbConnection; 24 | 25 | // public function __construct(MySQLConnection $dbConnection) 26 | // { 27 | // $this->dbConnection = $dbConnection; 28 | // } 29 | 30 | // // Faz alguma coisa 31 | // } 32 | 33 | 34 | 35 | // use MySQLConnection; 36 | 37 | // class PasswordReminder 38 | // { 39 | // private $dbConnection; 40 | 41 | // public function __construct(MySQLConnection $dbConnection) 42 | // { 43 | // $this->dbConnection = $dbConnection; 44 | // } 45 | 46 | // // Faz alguma coisa 47 | // } 48 | // view raw 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | // interface DBConnectionInterface 60 | // { 61 | // public function connect(); 62 | // } 63 | 64 | 65 | // class MySQLConnection implements DBConnectionInterface 66 | // { 67 | // public function connect() 68 | // { 69 | // // ... 70 | // } 71 | // } 72 | 73 | // class OracleConnection implements DBConnectionInterface 74 | // { 75 | // public function connect() 76 | // { 77 | // // ... 78 | // } 79 | // } 80 | 81 | // class PasswordReminder 82 | // { 83 | // private $dbConnection; 84 | 85 | // public function __construct(DBConnectionInterface $dbConnection) { 86 | // $this->dbConnection = $dbConnection; 87 | // } 88 | 89 | // // Faz alguma coisa 90 | // } -------------------------------------------------------------------------------- /projects-php/php-design-patterns/src/DependencyInversion2.php: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RazielRodrigues/php-projects/551e08b0b6aafea510a004dab9268b88c1b627f7/projects-php/php-design-patterns/src/DependencyInversion2.php -------------------------------------------------------------------------------- /projects-php/php-design-patterns/src/InterfaceSegragation.php: -------------------------------------------------------------------------------- 1 | setLocalizacao(100, 200); 47 | $pinguim->renderizar(); -------------------------------------------------------------------------------- /projects-php/php-design-patterns/src/LiskovSubstitution.php: -------------------------------------------------------------------------------- 1 | ensinando geral...'; 6 | } 7 | } 8 | 9 | class ProfessorFisica extends Professor{ 10 | function ensinar(){ 11 | echo '
ensinando fisica...'; 12 | } 13 | 14 | 15 | // Quebram o conceito de liskov 16 | // colocar esse metodo e deixar vazio? 17 | // function ensinar(){} 18 | 19 | // lançar uma expection 20 | // function ensinar(){ 21 | // throw new Exception; 22 | // } 23 | 24 | // trocar o tipo de retorno 25 | // function ensinar(){ 26 | // return 123; 27 | // } 28 | 29 | } 30 | 31 | $professor = new Professor(); 32 | $professorFisica = new ProfessorFisica(); 33 | 34 | function professorEnsina(Professor $professor){ 35 | $professor->ensinar(); 36 | } 37 | 38 | professorEnsina($professor); 39 | professorEnsina($professorFisica); -------------------------------------------------------------------------------- /projects-php/php-design-patterns/src/LiskovSubstitution2.php: -------------------------------------------------------------------------------- 1 | remuneracao(); 25 | 26 | # - Lançando uma exceção inesperada... 27 | class MusicPlay 28 | { 29 | public function play($file) 30 | { 31 | // toca a música 32 | } 33 | } 34 | 35 | class Mp3MusicPlay extends MusicPlay 36 | { 37 | public function play($file) 38 | { 39 | if (pathinfo($file, PATHINFO_EXTENSION) !== 'mp3') { 40 | throw new Exception; 41 | } 42 | 43 | // toca a música 44 | } 45 | } 46 | 47 | 48 | # - Retornando valores de tipos diferentes... 49 | class Auth 50 | { 51 | public function checkCredentials($login, $password) 52 | { 53 | // faz alguma coisa 54 | 55 | return true; 56 | } 57 | } 58 | 59 | class AuthApi extends Auth 60 | { 61 | public function checkCredentials($login, $password) 62 | { 63 | // faz alguma coisa 64 | 65 | return ['auth' => true, 'status' => 200]; 66 | } 67 | } -------------------------------------------------------------------------------- /projects-php/php-design-patterns/src/OpenClose.php: -------------------------------------------------------------------------------- 1 | salario'; 12 | } 13 | } 14 | 15 | class Estagio 16 | { 17 | public function bolsaAuxilio() 18 | { 19 | echo '
bolsaAuxilio'; 20 | } 21 | } 22 | 23 | class PJ 24 | { 25 | public function notafiscal() 26 | { 27 | echo '
notafiscal'; 28 | } 29 | } 30 | 31 | class FolhaDePagamento 32 | { 33 | protected $saldo; 34 | 35 | public function calcular($funcionario) 36 | { 37 | // se eu for adicionar mais um tipo de contrato 38 | // por exemplo freelance, vai precisar adicionar 39 | // outro if pra saber qual regra de negocio chamar 40 | // isso causa o conceito de acoplamento 41 | if ($funcionario instanceof ContratoClt) { 42 | $this->saldo = $funcionario->salario(); 43 | } else if ($funcionario instanceof Estagio) { 44 | $this->saldo = $funcionario->bolsaAuxilio(); 45 | } else if ($funcionario instanceof PJ) { 46 | $this->saldo = $funcionario->notafiscal(); 47 | } 48 | } 49 | } 50 | 51 | 52 | 53 | 54 | $estagiario = new Estagio(); 55 | $empregado = new ContratoClt(); 56 | $pj = new PJ(); 57 | 58 | $folhaDePagamento = new FolhaDePagamento(); 59 | $folhaDePagamento->calcular($estagiario); 60 | $folhaDePagamento->calcular($empregado); 61 | $folhaDePagamento->calcular($pj); 62 | 63 | echo '
'; 64 | 65 | /** 66 | * O conceito de open and closed esta muito perceptivel aqui 67 | * caso ele nao estive presente veriamos diversos if dentro da 68 | * folha de pagmento, invez disso foi usado uma interface 69 | * para fazer o codigo entender sem a necessidade de if, ou melhor 70 | * sem a classe que consome saber qual é a regra de negocio 71 | */ 72 | 73 | interface Remuneravel 74 | { 75 | public function remuneracao(); 76 | } 77 | 78 | class ContratoClt2 implements Remuneravel 79 | { 80 | public function remuneracao() 81 | { 82 | echo '
ContratoClt2'; 83 | } 84 | } 85 | 86 | class Estagio2 implements Remuneravel 87 | { 88 | public function remuneracao() 89 | { 90 | echo '
Estagio2'; 91 | } 92 | } 93 | 94 | class PJ2 implements Remuneravel 95 | { 96 | public function remuneracao() 97 | { 98 | echo '
PJ2'; 99 | } 100 | } 101 | 102 | class FolhaDePagamento2 103 | { 104 | protected $saldo; 105 | 106 | public function calcular(Remuneravel $funcionario) 107 | { 108 | $this->saldo = $funcionario->remuneracao(); 109 | } 110 | } 111 | 112 | $estagiario = new Estagio2(); 113 | $empregado = new ContratoClt2(); 114 | $pj = new PJ2(); 115 | 116 | $folhaDePagamento = new FolhaDePagamento2(); 117 | $folhaDePagamento->calcular($estagiario); 118 | $folhaDePagamento->calcular($empregado); 119 | $folhaDePagamento->calcular($pj); 120 | -------------------------------------------------------------------------------- /projects-php/php-design-patterns/src/OpenClose2.php: -------------------------------------------------------------------------------- 1 | misturar por 5 minutos'; 14 | // } 15 | // public function assar() 16 | // { 17 | // echo '
assar por 50 minutos'; 18 | // } 19 | // } 20 | 21 | // class BoloChocolate implements Bolo 22 | // { 23 | // public function misturar() 24 | // { 25 | // echo '
misturar por 2 minutos'; 26 | // } 27 | // public function assar() 28 | // { 29 | // echo '
assar por 30 minutos'; 30 | // } 31 | // } 32 | 33 | // class Sobremesa { 34 | // function levarSobremesa(Bolo $bolo){ 35 | // $bolo->misturar(); 36 | // $bolo->assar(); 37 | // } 38 | // } 39 | 40 | class BoloCenoura 41 | { 42 | public function misturar() 43 | { 44 | echo '
misturar por 5 minutos'; 45 | } 46 | public function assar() 47 | { 48 | echo '
assar por 50 minutos'; 49 | } 50 | } 51 | 52 | class BoloChocolate 53 | { 54 | public function misturar() 55 | { 56 | echo '
misturar por 2 minutos'; 57 | } 58 | public function assar() 59 | { 60 | echo '
assar por 30 minutos'; 61 | } 62 | } 63 | 64 | class Sobremesa { 65 | function levarSobremesa($bolo){ 66 | if ($bolo instanceof BoloCenoura) { 67 | $bolo->assar(); 68 | // if ($bolo->assar()) { 69 | echo ' cenoura é mais caro'; 70 | // } 71 | return; 72 | } 73 | $bolo->misturar(); 74 | $bolo->assar(); 75 | } 76 | } 77 | 78 | $bolo = new BoloCenoura(); 79 | $sobremesa = new Sobremesa(); 80 | 81 | $sobremesa->levarSobremesa($bolo); -------------------------------------------------------------------------------- /projects-php/php-design-patterns/src/SingleResposability.php: -------------------------------------------------------------------------------- 1 | id = $id; 15 | $this->username = $username; 16 | } 17 | 18 | public function create() 19 | { 20 | $user = [ 21 | $this->id, 22 | $this->username 23 | ]; 24 | 25 | var_dump($user); 26 | } 27 | 28 | public function sendEmail() 29 | { 30 | echo 'sending email to: ' . $this->username ; 31 | } 32 | 33 | } 34 | 35 | class UserSingleResposability 36 | { 37 | private $id; 38 | private $username; 39 | 40 | public function __construct($id, $username) { 41 | $this->id = $id; 42 | $this->username = $username; 43 | } 44 | 45 | public function create() 46 | { 47 | $user = [ 48 | $this->id, 49 | $this->username 50 | ]; 51 | 52 | var_dump($user); 53 | } 54 | 55 | /** 56 | * Get the value of username 57 | */ 58 | public function getUsername() 59 | { 60 | return $this->username; 61 | } 62 | 63 | /** 64 | * Set the value of username 65 | * 66 | * @return self 67 | */ 68 | public function setUsername($username) 69 | { 70 | $this->username = $username; 71 | 72 | return $this; 73 | } 74 | } 75 | 76 | class EmailSingleResposability 77 | { 78 | public $userSingleResposability; 79 | 80 | public function __construct(UserSingleResposability $userSingleResposability) { 81 | $this->userSingleResposability = $userSingleResposability; 82 | } 83 | 84 | public function sendEmail() 85 | { 86 | echo '
sending email to: ' . $this->userSingleResposability->getUsername() ; 87 | } 88 | 89 | 90 | } 91 | 92 | // wrong 93 | $raziel = new UserNotSingleResposability(1, 'Raziel Rodrigues Wrong'); 94 | $raziel->sendEmail() . '
'; 95 | 96 | // right 97 | $raziel = new UserSingleResposability(1, 'Raziel Rodrigues Right'); 98 | $email = new EmailSingleResposability($raziel); 99 | 100 | $email->sendEmail(); -------------------------------------------------------------------------------- /projects-php/php-design-patterns/src/index.php: -------------------------------------------------------------------------------- 1 | '; 5 | require_once 'OpenClose.php'; 6 | echo '
'; 7 | require_once 'OpenClose2.php'; 8 | echo '
'; 9 | require_once 'LiskovSubstitution.php'; 10 | echo '
'; 11 | require_once 'LiskovSubstitution2.php'; 12 | echo '
'; 13 | // require_once 'InterfaceSegragation.php'; 14 | echo '
'; 15 | require_once 'InterfaceSegragation2.php'; 16 | echo '
'; 17 | require_once 'DependencyInversion.php'; 18 | -------------------------------------------------------------------------------- /projects-php/php-design-patterns/summary.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RazielRodrigues/php-projects/551e08b0b6aafea510a004dab9268b88c1b627f7/projects-php/php-design-patterns/summary.png -------------------------------------------------------------------------------- /projects-php/php-form/README.md: -------------------------------------------------------------------------------- 1 | # Funções em PHP 2 | 3 | ## Declarando funções 4 | function validaNome(string $nome) : bool{ 5 | 6 | return true; 7 | } 8 | 9 | 1. Em uma função voce pode definir o tipo do retorno colocando : tipo_retorno 10 | 2. Com a função declare('strict type = 1') voce deixa o PHP com tipagem forte 11 | 3. Em PHP podemos declarar que um metodo pode receber string mas se ele precisar pode retornar null para isso basta adicionar o coringa ?string na frente do parametro de retorno. 12 | 4. A função unset ela destroi uma variavél, que está setada. 13 | 5. Após isso é necessario incluir os arquivos dentro do arquivo responsavel por receber os dados, assim como em C ou em JAVA. 14 | -------------------------------------------------------------------------------- /projects-php/php-form/images/php-logo.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /projects-php/php-form/index.php: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | PHP FORM 12 | 13 | 14 | 15 | 20 | 21 |
22 | 23 |
24 |

25 | 31 |

32 | 33 |

34 | 40 |

41 |
42 | 43 |
44 |
45 |

Ficha de inscrição

46 |
47 | 48 |
49 |
50 |
51 |
52 | 53 |
54 |
55 | 56 |
57 |
58 | 59 |
60 |
61 | 62 |
63 |
64 |
65 |
66 |
67 | 68 |
69 | 70 | 71 | 72 | 73 | -------------------------------------------------------------------------------- /projects-php/php-form/script.php: -------------------------------------------------------------------------------- 1 | Seu nome: '.$primeiroNome.' '.$segundoNome.'
Sua idade: '.$idade); 7 | return null; 8 | }else{ 9 | return getMensagemErro(); 10 | } 11 | 12 | } 13 | -------------------------------------------------------------------------------- /projects-php/php-form/servicos/servicoMensagemSessao.php: -------------------------------------------------------------------------------- 1 | Os campos não podem ser vazio!'); 8 | return false; 9 | }else if (strlen($primeiroNome) < 3 && strlen($segundoNome) < 3){ 10 | setMensagemErro('
Nome muito pequeno!'); 11 | return false; 12 | }else if (strlen($primeiroNome) > 40 || strlen($segundoNome) > 40){ 13 | setMensagemErro('
Nome muito extenso!'); 14 | return false; 15 | } 16 | 17 | return true; 18 | } 19 | 20 | function validaIdade(string $idade) : bool{ 21 | removerMensagemSucesso(); 22 | 23 | if (!is_numeric($idade)) { 24 | setMensagemErro('
Digite um número!'); 25 | return false; 26 | } 27 | 28 | return true; 29 | } 30 | -------------------------------------------------------------------------------- /projects-php/php-nif-validation/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM php:8.2-apache 2 | RUN docker-php-ext-install mysqli -------------------------------------------------------------------------------- /projects-php/php-nif-validation/README.md: -------------------------------------------------------------------------------- 1 | # VALIDAÇÃO DE NIF PORTUGUÊS (PHP PACKAGE) 2 | 3 | O Projeto tem o objetivo de validar o NIF Português utilizando as regras descritas abaixo: 4 | 5 | O NIF contém 9 dígitos, sendo o último o digito de controlo. Para ser calculado o digito de controlo: 6 | - Multiplique o 8.º dígito por 2, o 7.º dígito por 3, o 6.º dígito por 4, o 5.º dígito por 5, o 4.º dígito por 6, o 3.º dígito por 7, o 2.º dígito por 8 e o 1.º dígito por 9; 7 | - Some os resultados; 8 | - Calcule o resto da divisão do número por 11; 9 | - Se o resto for 0 (zero) ou 1 (um) o dígito de controlo será 0 (zero); 10 | - Se for outro qualquer algarismo X, o dígito de controlo será o resultado da subtracção 11 - X. 11 | 12 | ### SUBIR AMBIENTE LOCAL 13 | 14 | docker-compouse up -d 15 | acesse: http://localhost/index.php 16 | 17 | ### REFERÊNCIA 18 | 19 | https://pt.wikipedia.org/wiki/N%C3%BAmero_de_identifica%C3%A7%C3%A3o_fiscal 20 | https://www.nif.pt/ -------------------------------------------------------------------------------- /projects-php/php-nif-validation/docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: '3' 2 | 3 | services: 4 | php: 5 | build: . 6 | ports: 7 | - "80:80" 8 | - "443:443" 9 | volumes: 10 | - ./src:/var/www/html 11 | -------------------------------------------------------------------------------- /projects-php/php-nif-validation/src/index.php: -------------------------------------------------------------------------------- 1 | validateOnline(); 15 | } 16 | } 17 | ?> 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | VALIDADOR DE NIF | BY RAZIEL RODRIGUES 26 | 27 | 28 | 29 | 30 | 31 | 38 | 39 |
40 |
41 |
42 |
43 | 44 | 45 |
46 |
47 | 48 | 49 |
50 | 51 |
52 |
53 | 54 |
55 | 56 | validate()) { ?> 57 |

NIF Válido

58 |
Tipo: getNIFtype() ?>
59 | 60 |
61 | 62 |
63 | 64 | 65 |

NIF INVÁLIDO

66 | 67 | 68 |

O número de identificação fiscal (NIF) tem como finalidade identificar em Portugal uma entidade fiscal, contribuinte, por exemplo, em declarações de IRS ou outros impostos ou transações financeiras. 69 |

70 |
71 |
72 | 73 | 74 | 75 | 76 | -------------------------------------------------------------------------------- /projects-php/php-nif-validation/src/service/NIFValidationService.php: -------------------------------------------------------------------------------- 1 | razielx3@live.com 17 | */ 18 | class NIFValidationService implements NIFValidationServiceInterface 19 | { 20 | 21 | /** 22 | * Hold all types of NIF based in the first two numbers 23 | */ 24 | private array $NIFtypes = [ 25 | '1' => 'pessoa singular', 26 | '2' => 'pessoa singular', 27 | '3' => 'pessoa singular', 28 | '5' => 'pessoa colectiva', 29 | '6' => 'administração ', 30 | '8' => 'empresário em nome individual (extinto)', 31 | '45' => 'pessoa singular não residente', 32 | '70' => 'herança indivisa', 33 | '71' => 'pessoa colectiva não residente', 34 | '72' => 'fundos de investimento', 35 | '77' => 'atribuição oficiosa', 36 | '79' => 'regime excepcional', 37 | '90' => 'condominios e sociedades irregulares', 38 | '91' => 'condominios e sociedades irregulares', 39 | '98' => 'não residentes', 40 | '99' => 'sociedades civis' 41 | ]; 42 | 43 | public function __construct(private string $nif) 44 | { 45 | } 46 | 47 | /** 48 | * Check if NIF is following the rules 49 | * 50 | * @return bool 51 | */ 52 | public function validate(): bool 53 | { 54 | if (strlen($this->nif) < 9 || !is_numeric($this->nif)) { 55 | return false; 56 | } 57 | 58 | $NIFdigits = str_split($this->nif); 59 | 60 | $lastDigit = end($NIFdigits); 61 | if ($lastDigit == 0) { 62 | $lastDigit = 11; 63 | } 64 | 65 | $mustBeEqual = $this->calculateNIF(); 66 | 67 | return $lastDigit == $mustBeEqual; 68 | } 69 | 70 | /** 71 | * Do a call inside NIF.PT website 72 | * 73 | * @return string 74 | */ 75 | public function validateOnline(): string 76 | { 77 | $ch = curl_init(); 78 | curl_setopt($ch, CURLOPT_URL, "https://www.nif.pt/{$this->nif}"); 79 | curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 80 | $response = curl_exec($ch); 81 | 82 | $dom = new DOMDocument; 83 | $dom->loadHTML($response); 84 | 85 | foreach ($dom->getElementsByTagName('div') as $node) { 86 | $nifOnlineInfo[] = $dom->saveHTML($node); 87 | } 88 | 89 | curl_close($ch); 90 | 91 | return $nifOnlineInfo[9] ?? ''; 92 | } 93 | 94 | /** 95 | * Do the calc to match NIF rules 96 | * 97 | * @return int 98 | */ 99 | public function calculateNIF(): int 100 | { 101 | $sum = 0; 102 | $factorial = 9; 103 | $digits = str_split($this->nif); 104 | 105 | array_pop($digits); 106 | 107 | foreach ($digits as $digit) { 108 | $sum += $digit * $factorial; 109 | $factorial--; 110 | } 111 | 112 | $module = $sum % 11; 113 | 114 | $mustBeEqual = 0; 115 | if ($module !== 1 || $module !== 0) { 116 | $mustBeEqual = 11 - $module; 117 | } 118 | 119 | return $mustBeEqual; 120 | } 121 | 122 | /** 123 | * Return the type of nif based on the two first numbers 124 | * 125 | * @return string 126 | */ 127 | public function getNIFtype(): string 128 | { 129 | $normalPersonDigit = substr($this->nif, 0, 1); 130 | $businessDigit = substr($this->nif, 0, 2); 131 | return $this->NIFtypes[$normalPersonDigit] ?? $this->NIFtypes[$businessDigit]; 132 | } 133 | } 134 | -------------------------------------------------------------------------------- /projects-php/php-nif-validation/src/service/NIFValidationServiceInterface.php: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | PHP OO VENDAS 6 | 7 | 8 | exibirVendas(); 18 | 19 | $mercado->registrarVenda(12); 20 | 21 | echo $mercado->exibirVendas(); 22 | 23 | 24 | ?> 25 | 26 | -------------------------------------------------------------------------------- /projects-php/php-oo-2/challenge-vendas/vendas.class.php: -------------------------------------------------------------------------------- 1 | data = $data; 14 | $this->produto = $produto; 15 | $this->quantidazde = $quantidade; 16 | $this->valorTotal = $valorTotal; 17 | } 18 | 19 | public function exibirVendas() 20 | { 21 | 22 | return 23 | ""; 29 | } 30 | 31 | public function registrarVenda($venda) 32 | { 33 | $this->quantidade+=$venda; 34 | return "

Quantidade vendida = ".$venda."

"; 35 | } 36 | 37 | } 38 | -------------------------------------------------------------------------------- /projects-php/php-oo-2/exercicio-banco/ContaBancaria.class.php: -------------------------------------------------------------------------------- 1 | banco = $banco; 54 | 55 | $this->nomeTitular = $nomeTitular; 56 | 57 | $this->numeroAgencia = $numeroAgencia; 58 | 59 | $this->numeroConta = $numeroConta; 60 | 61 | $this->saldo = $saldo; 62 | } 63 | 64 | public function obterSaldo() 65 | { 66 | return '

Saldo atual: '.$this->saldo.'

'; 67 | } 68 | 69 | public function depositar($valor) 70 | { 71 | $this->saldo += $valor; 72 | return 'Deposito de R$ '.$valor.' realizado :)'; 73 | } 74 | 75 | public function saque($valor) 76 | { 77 | $this->saldo -= $valor; 78 | return 'Saque de R$ '.$valor.' realizado :)'; 79 | } 80 | 81 | } 82 | -------------------------------------------------------------------------------- /projects-php/php-oo-2/exercicio-banco/index.php: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | BANCO PHP 6 | 7 | 8 |
9 |

Bem vindo ao banco PHP!

10 |
11 |
12 | obterSaldo(); 24 | 25 | echo $conta->depositar(300.00); 26 | 27 | echo $conta->obterSaldo(); 28 | 29 | echo $conta->saque(150.00); 30 | 31 | echo $conta->obterSaldo(); 32 | 33 | 34 | ?> 35 |
36 | 37 | -------------------------------------------------------------------------------- /projects-php/php-oo-2/exercicio-date/index.php: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | DATE TIME 5 | 6 | 7 | format('D-M-Y H:i:s'); 14 | 15 | $data = new DateTime(); 16 | $intervalo = new DateInterval('PT5M'); 17 | 18 | $data->add($intervalo); 19 | var_dump($data); 20 | 21 | $data->sub($intervalo); 22 | var_dump($data); 23 | 24 | 25 | 26 | ?> 27 | 28 | -------------------------------------------------------------------------------- /projects-php/php-oo-2/exercicio-excecoes/index.php: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Exceções em PHP 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /projects-php/php-oo-2/exercicio-excecoes/validarUsuarioComExcecao.php: -------------------------------------------------------------------------------- 1 | 1, 16 | 'nome' => '', 17 | 'idade' => 43, 18 | 19 | ]; 20 | 21 | validarUsuario($usuario); 22 | -------------------------------------------------------------------------------- /projects-php/php-oo-2/exercicio-excecoes/validarUsuarioComTryCatch.php: -------------------------------------------------------------------------------- 1 | 1, 16 | 'nome' => '', 17 | 'idade' => 43, 18 | 19 | ]; 20 | 21 | $status = false; 22 | 23 | try{ 24 | $status = validarUsuario($usuario); 25 | } catch (Exception $e) { 26 | echo $e->getMessage(); 27 | }finally{ 28 | echo "

Status da operação = ".(int)$status; 29 | die(); 30 | } 31 | -------------------------------------------------------------------------------- /projects-php/php-oo-2/exercicio-excecoes/validarUsuarioSemExcecao.php: -------------------------------------------------------------------------------- 1 | 1, 16 | 'nome' => '', 17 | 'idade' => 43, 18 | 19 | ]; 20 | 21 | $usuarioValido = validarUsuario($usuario); 22 | 23 | if (!$usuarioValido) { 24 | echo "Usuario inválido"; 25 | return false; 26 | } 27 | 28 | 29 | -------------------------------------------------------------------------------- /projects-php/php-oo-2/exercicio-pdo/index.php: -------------------------------------------------------------------------------- 1 | listagem produtos:
"; 10 | foreach ($produto->list() as $value) { 11 | echo '
'.'ID:'. $value['id'].'
'.'Descricao:'.$value['descricao'].'
'; 12 | } 13 | 14 | break; 15 | 16 | case 'insert': 17 | $status = $produto->insert('Produto do biguinho'); 18 | 19 | if (!$status) { 20 | echo "deu errado!"; 21 | return false; 22 | } 23 | 24 | return header('location:index.php?operacao=list'); 25 | 26 | break; 27 | case 'update': 28 | 29 | 30 | $status = $produto->update('Produto do biguinho alterado', 4); 31 | 32 | if (!$status) { 33 | echo "deu errado!"; 34 | return false; 35 | } 36 | 37 | return header('location:index.php?operacao=list'); 38 | 39 | break; 40 | case 'delete': 41 | 42 | $status = $produto->delete(1); 43 | 44 | if (!$status) { 45 | echo "deu errado!"; 46 | return false; 47 | } 48 | 49 | return header('location:index.php?operacao=list'); 50 | 51 | break; 52 | default: 53 | 54 | header('location:index.php?operacao=list'); 55 | 56 | break; 57 | } 58 | -------------------------------------------------------------------------------- /projects-php/php-oo-2/exercicio-pdo/src/Produtos.class.php: -------------------------------------------------------------------------------- 1 | conexaoDB = new PDO('mysql:host=localhost;dbname=pdo','root',''); 12 | } catch (Exception $e) { 13 | $e->getMessage(); 14 | } 15 | 16 | } 17 | 18 | 19 | public function list(): array 20 | { 21 | 22 | $select = 'select * from produtos'; 23 | $produtos = []; 24 | foreach ($this->conexaoDB->query($select) as $key => $value) { 25 | array_push($produtos, $value); 26 | } 27 | 28 | return $produtos; 29 | } 30 | 31 | 32 | public function insert(string $descricao): int 33 | { 34 | 35 | $insert = 'insert into produtos(descricao) values(?)'; 36 | $prepare = $this->conexaoDB->prepare($insert); 37 | $prepare->bindParam(1, $descricao); 38 | $prepare->execute(); 39 | 40 | return $prepare->rowCount(); 41 | } 42 | 43 | public function update(string $descricao, int $id): int 44 | { 45 | 46 | $update = 'update produtos set descricao = ? where id = ?'; 47 | $prepare = $this->conexaoDB->prepare($update); 48 | $prepare->bindParam(1, $descricao); 49 | $prepare->bindParam(2, $id); 50 | $prepare->execute(); 51 | 52 | return $prepare->rowCount(); 53 | } 54 | 55 | public function delete(int $id): int 56 | { 57 | 58 | $delete = 'delete from produtos where id = ?'; 59 | $prepare = $this->conexaoDB->prepare($delete); 60 | $prepare->bindParam(1, $id); 61 | $prepare->execute(); 62 | 63 | return $prepare->rowCount(); 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /projects-php/php-oo-2/exercicio-pdo/src/old/connect.php: -------------------------------------------------------------------------------- 1 | getMessage(); 14 | die(); 15 | 16 | } 17 | 18 | return $conexaoDB; 19 | -------------------------------------------------------------------------------- /projects-php/php-oo-2/exercicio-pdo/src/old/deleteDB.php: -------------------------------------------------------------------------------- 1 | prepare($delete); 8 | $prepare->bindParam(1, $_GET['id']); 9 | 10 | $prepare->execute(); 11 | 12 | echo $prepare->rowCount(); 13 | -------------------------------------------------------------------------------- /projects-php/php-oo-2/exercicio-pdo/src/old/insertDB.php: -------------------------------------------------------------------------------- 1 | prepare($insert); 7 | 8 | $prepare->bindParam(1, $_GET['descricao']); 9 | $prepare->execute(); 10 | 11 | echo $prepare->rowCount(); 12 | -------------------------------------------------------------------------------- /projects-php/php-oo-2/exercicio-pdo/src/old/listDB.php: -------------------------------------------------------------------------------- 1 | listagem produtos:
"; 9 | 10 | foreach ($conexaoDB->query($select) as $key => $value) { 11 | echo '
'.'ID:'. $value['id'].'
'.'Descricao:'.$value['descricao'].'
'; 12 | } 13 | -------------------------------------------------------------------------------- /projects-php/php-oo-2/exercicio-pdo/src/old/updateDB.php: -------------------------------------------------------------------------------- 1 | prepare($update); 9 | 10 | $prepare->bindParam(1, $_GET['descricao']); 11 | $prepare->bindParam(2, $_GET['id']); 12 | 13 | $prepare->execute(); 14 | 15 | echo $prepare->rowCount(); 16 | -------------------------------------------------------------------------------- /projects-php/php-oo-2/index.php: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Document 8 | 9 | 10 |
11 |

CONCEITOS PHP

12 | 13 | VENDAS 14 | BANCO 15 | DATE 16 | EXECECOES 17 | PDO 18 | OO OLD 19 | 20 |
21 |
22 | 23 | 24 | -------------------------------------------------------------------------------- /projects-php/php-oo-2/oo-old/Pessoa.php: -------------------------------------------------------------------------------- 1 | nome = $tmpnome; 13 | } 14 | 15 | // public function falarNome(){ 16 | // echo $this->nome; 17 | // } 18 | 19 | public function setNome($novoNome){ 20 | $this->nome = $novoNome; 21 | } 22 | 23 | public function getNome(){ 24 | return $this->nome; 25 | } 26 | 27 | } 28 | 29 | -------------------------------------------------------------------------------- /projects-php/php-oo-2/oo-old/Programador.php: -------------------------------------------------------------------------------- 1 | nome = $tmpnome; 9 | $this->linguagem = $tmplinguagem; 10 | 11 | echo "
Objeto".__CLASS__." foi instanciado.
"; 12 | #CONSTANTE MÁGICA 13 | } 14 | 15 | } -------------------------------------------------------------------------------- /projects-php/php-oo-2/oo-old/conecta.php: -------------------------------------------------------------------------------- 1 | getNome(); 8 | // Herança 9 | 10 | // Contante 11 | // echo $programador::ESPECIE; 12 | 13 | #NAMESPACE FAZ EVUTAR CONFLITO COM NOME DE FUNÇÃO 14 | 15 | include "conecta.php"; 16 | include "conecta2.php"; 17 | 18 | conectaSite\conecta(); -------------------------------------------------------------------------------- /projects-php/php-oo/page1.php: -------------------------------------------------------------------------------- 1 |

Membros estaticos

2 | 3 | naoStatic}
"; 15 | // tentativa 1 nao se acessa pelo $this pois this se referencia ao valor do objeto que instanciou 16 | // echo " estatica = {$this->static}"; 17 | // tentativa 2 nao funciona interpolação 18 | // echo " estatica = {self::$static}"; 19 | // tentativa 3 acessado por concatenação 20 | echo "estatica = ".self::$static."
"; 21 | } 22 | 23 | //! Dentro de uma função static so se consegue acessar membros estaticos 24 | public static function mostrarStaticA(){ 25 | // echo "nao estatica = {$this->naoStatic}
"; 26 | echo "estatica = ".self::$static."
"; 27 | } 28 | 29 | } 30 | 31 | // ! Comentando pra mostrar a diferança entre acessar coisas estaticas linha 36 32 | // $objA = new A(); 33 | // $objA->mostrarA(); 34 | 35 | //! $objA->mostrarStaticA(); da pra acessar instanciando um objeto e fazendo dessa forma, mas não é ideal. 36 | 37 | //! acessando funções estaticas 38 | //! membros e funções estaticas nao é necessario instanciar um objeto para chamar 39 | echo A::$static , '
'; //? Acesar diretamente pela classe 40 | A::mostrarStaticA(); //? Acesar diretamente pela classe 41 | //! Lembrando que o ideal é acessar mebros de classe com essa notação uma vez que deixa mais claro 42 | //! Logo que mebros staticos fazem parte da classe e nao do objeto, 43 | //! deixando de livre acesso pra fora do codigo, claro dependen do nivel de acesso 44 | 45 | //? Tambem é possivel alterar os valores dos membros da classe. 46 | A::$static = '
valor alterado do membro da classe '; 47 | echo A::$static; -------------------------------------------------------------------------------- /projects-php/php-oo/page2.php: -------------------------------------------------------------------------------- 1 |

Visibilidade (Encapsulamento)

2 | 3 | naoMostrar(); 21 | 22 | echo "Class a) Publico = {$this->publico}
"; 23 | echo "Class a) Protegido = {$this->protegido}
"; 24 | echo "Class a) Privado = {$this->privado}
"; 25 | } 26 | 27 | //! So vou acessar aqui dentro mesmo 28 | private function naoMostrar(){ 29 | echo "Nao mostrar
"; 30 | } 31 | 32 | //! Pode ser acessado pela classe que herdar 33 | protected function vaiPorHerança(){ 34 | echo "Por herança"; 35 | } 36 | 37 | } 38 | 39 | $a = new A(); 40 | $a->mostrarA(); 41 | //! Aqui da erro porque o metodo é privado 42 | // $a->naoMostrar(); 43 | 44 | 45 | //? Sempre pensar no maior nivel de restribilidade das varaveisi e metodos dentro de uma classe, 46 | //? isso demonstra maturidade no seu codigo 47 | class B extends A{ 48 | public function mostrarB() { 49 | echo "Class B) Publico = {$this->publico}
"; 50 | echo "Class B) Protegido = {$this->protegido}
"; 51 | // echo "Class B) Privado = {$this->privado}
"; 52 | parent::vaiPorHerança(); 53 | } 54 | } 55 | 56 | $b = new B(); 57 | //! Chamar usando B cnonceito de herança 58 | // $b->mostrarA(); 59 | $b->mostrarB(); 60 | // $b->naoMostrar(); 61 | -------------------------------------------------------------------------------- /projects-php/php-oo/page3.php: -------------------------------------------------------------------------------- 1 |

Interface

2 | 3 | respirar(); 64 | echo $animal->latir(); 65 | echo $animal->mamar(); 66 | 67 | //? Testes para mostrar como funciona as interfaces 68 | //? e o operador instanceof que retorna bool para quando um objeto nao faz parte da instancia (Felino) 69 | var_dump($animal); 70 | var_dump($animal instanceof Cachorro); 71 | var_dump($animal instanceof Canino); 72 | 73 | //! Por conta disso é possivel usar o metodo correr igual 74 | var_dump($animal instanceof Felino); -------------------------------------------------------------------------------- /projects-php/php-oo/page4.php: -------------------------------------------------------------------------------- 1 |

Classes abstratas

2 | public 7 | 8 | abstract class Abstrata { 9 | 10 | //? Pode ser definido apenas o corpo da função e seus parametros, tipagem, visibilidade 11 | abstract public function metodo1(); 12 | abstract protected function metodo2($parametro); 13 | 14 | } 15 | 16 | //? Classes abstratas podem ter herança 17 | abstract class FilhaAbstrata extends Abstrata{ 18 | 19 | //? Modificando o metodo da classe Abstrata e executando ele por override mesmo 20 | public function metodo1() { 21 | echo 'executando metodo 1 herdado de abstrata em Filha abstrata
'; 22 | } 23 | 24 | //? Esse metodo vai ser acessado na concreta 25 | abstract public function metodo3(); 26 | 27 | } 28 | 29 | //! Classes concretas podem herdar classes abstratas, sempre relação de um pra um. 30 | //! Quando voce implementa uma classe abstrata dentro de uma concreta voce é obrigado 31 | //! A definir os metodos pré existentes nas classes abstratas herdadas senao da erro. 32 | class Concreta extends FilhaAbstrata{ 33 | 34 | //! Metodo Abstrata 35 | public function metodo1(){ 36 | echo "Executando metodo 1 da classe {Abstrata} dentro de Concreta
"; 37 | echo "Executando metodo 1 com parent ou seja pegando da classe Filha Abstrata, pois usou extends
"; 38 | parent::metodo1(); 39 | } 40 | 41 | //! Metodo Abstrata 42 | 43 | /* 44 | ? Caso eu queira é possivel alterar o nivel de visibilidade como havia dito 45 | ? Se executar com public da certo. 46 | ? Mas nao é possivel abaixar o nivel de acesso. 47 | public function metodo2($parametro){ 48 | */ 49 | protected function metodo2($parametro){ 50 | echo "Executando metodo 2, com o parametro ( $parametro ) esse metodo é herdado da classe Abstrata
"; 51 | } 52 | 53 | //! Metodo Filha Abstrata 54 | public function metodo3(){ 55 | echo "Executando metodo 3 que vem da classe FilhaAbstrata
"; 56 | 57 | //? Alterando o metodo2 interno 58 | $this->metodo2('interno'); 59 | } 60 | 61 | 62 | } 63 | 64 | 65 | $c = new Concreta(); 66 | $c->metodo1(); 67 | $c->metodo3(); 68 | 69 | echo "Dumps:"; 70 | 71 | var_dump($c); 72 | var_dump($c instanceof Concreta); 73 | var_dump($c instanceof Abstrata); 74 | var_dump($c instanceof FilhaAbstrata); -------------------------------------------------------------------------------- /projects-php/php-oo/page5.php: -------------------------------------------------------------------------------- 1 |

Modificador final

2 | nao vou mudar pois sou final e to executando da classe Abstrata"; 14 | } 15 | 16 | } 17 | 18 | class Classe extends Abstrata{ 19 | 20 | public function metodo1(){ 21 | echo "
executar metodo 1 da classe {Classe}"; 22 | } 23 | 24 | // public function metodo2(){ 25 | // echo 'extends metodo 2 final tentando mudar e deu erro'; 26 | // } 27 | 28 | } 29 | 30 | $classe = new Classe; 31 | $classe->metodo1(); 32 | 33 | //? vai executar o metodo que foi extendid da classe Abstrata 34 | //? nao ocorreu o override, pois ia gerar erro. 35 | $classe->metodo2(); 36 | 37 | //? É possivel intanciar uma classe final, mas nao herdala, senão iria gerar um erro igual do metodo. 38 | final class Unica{ 39 | public $attr = '
Valoe dinamico classe Unica'; 40 | } 41 | 42 | //! Erro de extensão 43 | // class Teste extends Unica{} 44 | 45 | //? Instanciando uma classe final, normal. 46 | $unica = new Unica(); 47 | echo $unica->attr; -------------------------------------------------------------------------------- /projects-php/php-oo/page6.php: -------------------------------------------------------------------------------- 1 |

Traits

2 | validarString(' ')); // gera erro 13 | - ex (certo): 14 | 15 | */ 16 | trait validacao{ 17 | 18 | public $a = 'Valor A'; 19 | public function validarString($str){ 20 | return isset($str) && $str !== ''; 21 | } 22 | 23 | public function myNull($p){ 24 | return empty($p); 25 | } 26 | 27 | } 28 | 29 | trait validacaoMelhor{ 30 | public $b = 'Valor B'; 31 | private $c = 'Valor Privado da trait validacaoMelhor'; 32 | 33 | public function validarStringMelhor($str){ 34 | return isset($str) && trim($str); 35 | } 36 | 37 | public function myNull($p){ 38 | return empty($p); 39 | } 40 | 41 | } 42 | 43 | class Usuario { 44 | 45 | use validacao, validacaoMelhor{ 46 | validacaoMelhor::myNull insteadof validacao; 47 | // validacao::myNull insteadof validacaoMelhor; 48 | validacao::myNull as myNull2; 49 | } 50 | 51 | public function imprimirC(){ 52 | return $this->c; 53 | } 54 | 55 | } 56 | 57 | //? tentando acessar direto pelo nome da trait 58 | // var_dump(validacao->validarString(' ')); 59 | 60 | $usuario = new Usuario(); 61 | var_dump($usuario->validarString(' ')); 62 | var_dump($usuario->validarStringMelhor(' ')); 63 | echo $usuario->a, '
', $usuario->b; 64 | echo '
',$usuario->imprimirC(); 65 | $s = ''; 66 | var_dump($usuario->myNull($s)); -------------------------------------------------------------------------------- /projects-php/php-oo/page7.php: -------------------------------------------------------------------------------- 1 |

Metodos magicos

2 | '; 9 | $this->nome = $nome; 10 | $this->idade = $idade; 11 | } 12 | 13 | public function __destruct(){ 14 | return 'liberado
'; 15 | } 16 | 17 | /* 18 | ? Esse metodo transforma o contexto do objeto em string de forma que, 19 | ? seja possivel renderizar o objeto apontando para $this 20 | ? Transforma os atributos em string 21 | */ 22 | public function __toString(){ 23 | return "{$this->nome} tem {$this->idade} anos"; 24 | } 25 | 26 | //! Acessando objeto apenas com o $this pois o objeto inteiro virou uma string 27 | public function apresentar(){ 28 | echo $this . "
"; 29 | } 30 | 31 | /* 32 | ? o metodo get é ativado quando nao existe o atributo na classe 33 | ? e mesmo assim voce tenta acessar. ou seja ali embaixo eu tentei 34 | ? acessar nome completo e nao existe esse atributo declarado. 35 | ? agora o que vai acontecer e que pro metodo __get será enviado essa informaçao 36 | ? ou seja "nomeCompleto". 37 | 38 | ! Com isso é possivel manipular essas requisições de atributos que não existem. 39 | */ 40 | public function __get($atr){ 41 | echo "Tentando acessar atributo não declarado: {$atr} quer fazer algo?
"; 42 | } 43 | 44 | /* 45 | ? O metodo __set cria novos atributos quando eles não existem de forma que os parametros são 46 | ? atr = nome do atributo que não existe 47 | ? val = valor dado a esse atributo 48 | */ 49 | public function __set($atr, $val){ 50 | echo "Criando atributo não declarado: {$atr} / {$val}"; 51 | } 52 | 53 | /* 54 | ? __call é chamado quando tenta executar um metodo que não existe 55 | ? caso voce passe parametros para esse metodo os parametros 56 | ? vão se tornar um array dentro dessa função. 57 | 58 | ! Tem a mesma ideia de manipular dos outros metodos 59 | */ 60 | public function __call($metodo, $params){ 61 | echo "tentando executar metodo inexistente: {$metodo} com os parametros:"; 62 | print_r($params); 63 | } 64 | 65 | } 66 | 67 | $pessoa = new Pessoa('Raziel', 22); 68 | //? teste toString: $pessoa->apresentar() ou echo $pessoa; 69 | //? teste __get: $pessoa->nomeCompleto; 70 | //? teste __set: $pessoa->nomeCompleto = "Raziel Rodrigues"; 71 | //? teste 1 __call: $pessoa->exec(); 72 | //? teste 2 __call: $pessoa->exec(true, 123, 'abc', ['teste',234,false]); //? Passando com parametros 73 | // ! metodos magicos não uma coisa padrão então deve pensar bem antes de usar -------------------------------------------------------------------------------- /projects-php/php-oo/page8.php: -------------------------------------------------------------------------------- 1 |

Polimorfismo:

2 | peso = $peso; 32 | } 33 | 34 | 35 | /* 36 | ? O segredo está em qual parametro voce vai passar para a função 37 | ? como eu passei Comida qualquer classe que tenha herança de Comida 38 | ? será aceita pela função. 39 | 40 | ? Ou seja serve para amarrar os tipos qur vão entrar na função 41 | ? Mas o PHP já é uma linguagens que trabalha assim naturalmente. 42 | 43 | */ 44 | public function comer(Comida $comida){ 45 | $this->peso += $comida->peso; 46 | } 47 | 48 | } 49 | 50 | $almoco = new Arroz(); 51 | $almoco->peso = 0.20; 52 | 53 | $janta = new ArrozAgrega(); 54 | $janta->peso = 0.10; 55 | 56 | $ceia = new Sorvete(); 57 | $ceia->peso = 1.50; 58 | 59 | $suco = new Suco(); 60 | $suco->peso = 0.20; 61 | 62 | $raziel = new Pessoa(65.00); 63 | $raziel->comer($almoco); 64 | $raziel->comer($janta); 65 | $raziel->comer($ceia); 66 | 67 | 68 | //! gera erro $raziel->comer($suco); 69 | echo $raziel->peso; -------------------------------------------------------------------------------- /projects-php/php-search/.gitignore: -------------------------------------------------------------------------------- 1 | /view/storage -------------------------------------------------------------------------------- /projects-php/php-search/README.md: -------------------------------------------------------------------------------- 1 | # PHP SEARCH ENGINE PROJECT 2 | 3 | Thanks to share knowledge 4 | - https://www.udemy.com/course/draft/155640/learn/lecture/910932#content 5 | - https://linkedin.com/in/abdul-wali-94352445/ 6 | 7 | ## 1:Introduction - and creating necessary folders & display Page 8 | 9 | -------------------------------------------------------------------------------- /projects-php/php-search/controller/InsertController.php: -------------------------------------------------------------------------------- 1 | data = $database->query($sql)->fetchAll(); 14 | } catch (PDOException $e) { 15 | print "Error with database!: " .__FILE__. $e->getMessage() . "
"; 16 | die(); 17 | } 18 | } 19 | 20 | function getAll(){ 21 | return $this->data; 22 | } 23 | 24 | } -------------------------------------------------------------------------------- /projects-php/php-search/index.php: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | PHP SEARCH ENGINE PROJECT: SEARCH PAGE 7 | 8 | 9 | 10 | 11 | 12 |
13 | 31 |
32 | 33 | 34 | 35 | -------------------------------------------------------------------------------- /projects-php/php-search/model/db.php: -------------------------------------------------------------------------------- 1 | host, $this->user, $this->password); 14 | } catch (PDOException $e) { 15 | print "Error with database!: " .__FILE__. $e->getMessage() . "
"; 16 | die(); 17 | } 18 | } 19 | 20 | public function constructSearchTable() { 21 | $sql = "CREATE TABLE `search`.`sites` ( 22 | `site_id` INT NOT NULL AUTO_INCREMENT, 23 | `site_title` VARCHAR(240) NOT NULL, 24 | `site_link` VARCHAR(240) NOT NULL, 25 | `site_keyword` TEXT(500) NULL, 26 | `site_desc` TEXT(100) NULL, 27 | `site_image` TEXT(100) NULL, 28 | PRIMARY KEY (`site_id`)) 29 | ENGINE = InnoDB 30 | DEFAULT CHARACTER SET = utf8; 31 | "; 32 | return $this->db->query($sql); 33 | } 34 | 35 | public function insertSearch( 36 | $site_title, 37 | $site_link, 38 | $site_keyword, 39 | $site_description, 40 | $_site_image, 41 | $_site_image_tmp 42 | ){ 43 | 44 | } 45 | 46 | 47 | 48 | } -------------------------------------------------------------------------------- /projects-php/php-search/view/assets/css/main.css: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RazielRodrigues/php-projects/551e08b0b6aafea510a004dab9268b88c1b627f7/projects-php/php-search/view/assets/css/main.css -------------------------------------------------------------------------------- /projects-php/php-search/view/assets/js/main.js: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RazielRodrigues/php-projects/551e08b0b6aafea510a004dab9268b88c1b627f7/projects-php/php-search/view/assets/js/main.js -------------------------------------------------------------------------------- /projects-php/php-search/view/front/footer.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /projects-php/php-search/view/front/header.php: -------------------------------------------------------------------------------- 1 |
2 | 7 |
-------------------------------------------------------------------------------- /projects-php/php-search/view/front/home.php: -------------------------------------------------------------------------------- 1 | TODO - LOGO 2 |
3 | 4 | 5 |
-------------------------------------------------------------------------------- /projects-php/php-search/view/front/results.php: -------------------------------------------------------------------------------- 1 | getAll(); 6 | foreach ($result as $row) { 7 | echo ""; 8 | echo ""; 9 | echo ""; 10 | echo ""; 11 | echo ""; 12 | echo ""; 13 | echo ""; 14 | echo ""; 15 | echo ""; 16 | echo ""; 17 | echo ""; 18 | echo ""; 19 | echo ""; 20 | echo ""; 21 | echo ""; 22 | echo ""; 23 | echo ""; 24 | echo ""; 25 | echo "
".$row['site_title']."
".$row['site_link']."
".$row['site_keyword']."
".$row['site_description']."
".$row['site_image']."
"; 26 | } 27 | ?> -------------------------------------------------------------------------------- /projects-php/php-swoole/docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: '3' 2 | services: 3 | swoole-app: 4 | image: openswoole/swoole:latest-dev 5 | ports: 6 | - "8081:8081" 7 | volumes: 8 | - .:/var/www 9 | -------------------------------------------------------------------------------- /projects-php/php-swoole/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | Swoole Socket Client 9 | 22 | 23 | 24 | 25 |

Chat

26 |
27 |
28 | 29 | 30 | 31 |
32 | 33 | 65 | 66 | 67 | -------------------------------------------------------------------------------- /projects-php/php-swoole/server.php: -------------------------------------------------------------------------------- 1 | on('start', function (Server $server) { 12 | echo "WebSocket Server is listening on {$server->host}:{$server->port}", PHP_EOL; 13 | }); 14 | 15 | $server->on('open', function (Server $server, Request $request) { 16 | echo "Client connected: {$request->fd}", PHP_EOL; 17 | }); 18 | 19 | $server->on('message', function (Server $server, Frame $frame) { 20 | echo "Client {$frame->fd} message: {$frame->data}", PHP_EOL; 21 | 22 | foreach ($server->connections as $connection) { 23 | if ($connection === $frame->fd) { 24 | continue; 25 | } 26 | 27 | $server->push($connection, $frame->data); 28 | } 29 | }); 30 | 31 | $server->on('close', function (Server $server, int $fd) { 32 | echo "Client disconnected: {$fd}", PHP_EOL; 33 | }); 34 | 35 | $server->start(); 36 | -------------------------------------------------------------------------------- /projects-php/php-tips/.gitignore: -------------------------------------------------------------------------------- 1 | tip6 2 | # Vercel 3 | .vercel 4 | -------------------------------------------------------------------------------- /projects-php/php-tips/README.md: -------------------------------------------------------------------------------- 1 | # 30 tips of code PHP 2 | 3 | I'm gathering in this repository some tips, or I would also say curiosities, about PHP. Here, I'll accumulate random knowledge about the language, which will allow us to add small tools to our Swiss army knife. 4 | 5 | # Tech Stack 6 | 7 | There are some tips with Symfony and others with pure PHP. 8 | 9 | # Getting started 10 | 11 | docker compose up || php -S localhost:8080 index.php || symfony console server:start 12 | -------------------------------------------------------------------------------- /projects-php/php-tips/api/index.php: -------------------------------------------------------------------------------- 1 | time(), 'date' => date('d.m.Y'), 'tech' => 'Vercel']); 4 | -------------------------------------------------------------------------------- /projects-php/php-tips/docker-compose.yaml: -------------------------------------------------------------------------------- 1 | services: 2 | php: 3 | image: dunglas/frankenphp 4 | # uncomment the following line if you want to use a custom Dockerfile 5 | #build: . 6 | # uncomment the following line if you want to run this in a production environment 7 | restart: always 8 | ports: 9 | - "80:80" # HTTP 10 | - "443:443" # HTTPS 11 | - "443:443/udp" # HTTP/3 12 | volumes: 13 | - ./:/app/public 14 | - caddy_data:/data 15 | - caddy_config:/config 16 | environment: 17 | - FRANKENPHP_CONFIG="worker ./public/index.php" 18 | # comment the following line in production, it allows to have nice human-readable logs in dev 19 | tty: true 20 | 21 | # Volumes needed for Caddy certificates and configuration 22 | volumes: 23 | caddy_data: 24 | caddy_config: 25 | -------------------------------------------------------------------------------- /projects-php/php-tips/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | Vercel + PHP 9 | 10 | 11 | 12 | 13 |
14 |
15 | Vercel + PHP 16 | 17 | Deploy to Vercel 18 | 19 |
20 | 21 |

Use the deploy button or follow these steps.

22 | 23 |
    24 |
  1. Clone repository git clone git@github.com:vercel-community/php.git
  2. 25 |
  3. Switch to /php folder and run vercel
  4. 26 |
  5. Open generated *.vercel.app domain [demo]
  6. 27 |
  7. Discover *.vercel.app/api/ PHP functions [demo]
  8. 28 |
29 |
30 | 31 | 32 | 33 | -------------------------------------------------------------------------------- /projects-php/php-tips/tip1/generator.php: -------------------------------------------------------------------------------- 1 | Generators:
'; 16 | 17 | # USO BÁSICO 18 | function yieldCall() 19 | { 20 | for ($i = 0; $i < 10; $i++) { 21 | yield $i; 22 | } 23 | } 24 | 25 | $generator = yieldCall(); 26 | var_dump($generator); 27 | 28 | foreach ($generator as $value) { 29 | echo $value; 30 | } 31 | 32 | echo '
'; 33 | 34 | $csv = 'nome;raziel'; 35 | 36 | function parserYield($input) 37 | { 38 | foreach (explode(';', $input) as $key => $value) { 39 | yield uniqid() => $value; 40 | } 41 | } 42 | 43 | foreach (parserYield($csv) as $key => $value) { 44 | echo ($key); 45 | echo '
'; 46 | echo $value; 47 | } 48 | 49 | echo '
'; 50 | 51 | function &genYield() 52 | { 53 | $value = 3; 54 | 55 | while ($value > 0) { 56 | yield $value; 57 | } 58 | } 59 | 60 | foreach (genYield() as &$key) { 61 | echo (--$key); 62 | } 63 | 64 | echo '
'; 65 | 66 | class Test 67 | { 68 | } 69 | 70 | function y() 71 | { 72 | yield 3; 73 | yield 4; 74 | } 75 | 76 | function x() 77 | { 78 | yield 1; 79 | yield from y(); 80 | } 81 | 82 | 83 | $x = x(); 84 | 85 | foreach ($x as $value) { 86 | var_dump($value); 87 | } 88 | 89 | $x->getReturn(); 90 | 91 | var_dump(is_array($x->getReturn())); 92 | 93 | echo '
'; 94 | 95 | echo '

Exemplo benchmark:


'; 96 | 97 | 98 | function forEachOnly() 99 | { 100 | $numeros = []; 101 | foreach (range(1, 1000000) as $value) { 102 | $numeros[] = $value; 103 | } 104 | 105 | echo "Memory peak usage FOREACH: " . memory_get_peak_usage(true) . " bytes \n"; 106 | } 107 | 108 | function generatorCall() 109 | { 110 | foreach (range(1, 1000000) as $value) { 111 | yield $value; 112 | } 113 | } 114 | 115 | function generatorOnly() 116 | { 117 | foreach (generatorCall() as $value) { 118 | $value; 119 | } 120 | echo "Memory peak usage GENERATOR: " . memory_get_peak_usage(true) . " bytes \n"; 121 | } 122 | 123 | #forEachOnly(); 124 | #generatorOnly(); 125 | -------------------------------------------------------------------------------- /projects-php/php-tips/tip2/fibers.php: -------------------------------------------------------------------------------- 1 | Fibers:
'; 24 | 25 | $horas = 9; 26 | $pessoaQueTrabalha = new Fiber(function ($horas) { 27 | echo "\n Inicio trabalho às: {$horas}"; 28 | Fiber::suspend(); 29 | echo "\n Voltou a trabalhar"; 30 | return "o trabalhador se sente cansado!"; 31 | }); 32 | 33 | $emprego = new Fiber(function ($pessoaQueTrabalha, $horas) { 34 | $pessoaQueTrabalha->start($horas); 35 | 36 | if ($pessoaQueTrabalha->isSuspended()) { 37 | echo "\n Pessoa fez uma pausa"; 38 | } 39 | 40 | for ($i = 0; $i <= 8; $i++) { 41 | $horas++; 42 | if ($horas == 12) { 43 | $pessoaQueTrabalha->resume(); 44 | } 45 | } 46 | 47 | if ($pessoaQueTrabalha->isTerminated()) { 48 | echo "\n Pessoa terminou o trabalho às: {$horas}"; 49 | echo "\n Sentimentos pessoa: {$pessoaQueTrabalha->getReturn()}"; 50 | } 51 | }); 52 | 53 | $emprego->start($pessoaQueTrabalha, $horas); 54 | -------------------------------------------------------------------------------- /projects-php/php-tips/tip3/attributes.php: -------------------------------------------------------------------------------- 1 | Attributes:
'; 4 | 5 | #[Attribute] 6 | class Route 7 | { 8 | public function __construct($nome) 9 | { 10 | } 11 | } 12 | 13 | #[Route('/home')] 14 | class HomeController 15 | { 16 | } 17 | 18 | $reflector = new \ReflectionClass(HomeController::class); 19 | $attrs = $reflector->getAttributes(); 20 | 21 | foreach ($attrs as $attriubute) { 22 | var_dump($attriubute->getName()); 23 | var_dump($attriubute->getArguments()); 24 | var_dump($attriubute->getTarget()); 25 | var_dump($attriubute->newInstance()); 26 | } 27 | -------------------------------------------------------------------------------- /projects-php/php-tips/tip5/.env: -------------------------------------------------------------------------------- 1 | # In all environments, the following files are loaded if they exist, 2 | # the latter taking precedence over the former: 3 | # 4 | # * .env contains default values for the environment variables needed by the app 5 | # * .env.local uncommitted file with local overrides 6 | # * .env.$APP_ENV committed environment-specific defaults 7 | # * .env.$APP_ENV.local uncommitted environment-specific overrides 8 | # 9 | # Real environment variables win over .env files. 10 | # 11 | # DO NOT DEFINE PRODUCTION SECRETS IN THIS FILE NOR IN ANY OTHER COMMITTED FILES. 12 | # https://symfony.com/doc/current/configuration/secrets.html 13 | # 14 | # Run "composer dump-env prod" to compile .env files for production use (requires symfony/flex >=1.2). 15 | # https://symfony.com/doc/current/best_practices.html#use-environment-variables-for-infrastructure-configuration 16 | 17 | ###> symfony/framework-bundle ### 18 | APP_ENV=dev 19 | APP_SECRET=aa5c21c9e19bd980293fe2af978afc07 20 | ###< symfony/framework-bundle ### 21 | -------------------------------------------------------------------------------- /projects-php/php-tips/tip5/.gitignore: -------------------------------------------------------------------------------- 1 | 2 | ###> symfony/framework-bundle ### 3 | /.env.local 4 | /.env.local.php 5 | /.env.*.local 6 | /config/secrets/prod/prod.decrypt.private.php 7 | /public/bundles/ 8 | /var/ 9 | /vendor/ 10 | ###< symfony/framework-bundle ### 11 | -------------------------------------------------------------------------------- /projects-php/php-tips/tip5/bin/console: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env php 2 | =8.2", 8 | "ext-ctype": "*", 9 | "ext-iconv": "*", 10 | "symfony/console": "7.0.*", 11 | "symfony/dotenv": "7.0.*", 12 | "symfony/flex": "^2", 13 | "symfony/framework-bundle": "7.0.*", 14 | "symfony/runtime": "7.0.*", 15 | "symfony/yaml": "7.0.*" 16 | }, 17 | "require-dev": { 18 | "symfony/maker-bundle": "^1.57" 19 | }, 20 | "config": { 21 | "allow-plugins": { 22 | "php-http/discovery": true, 23 | "symfony/flex": true, 24 | "symfony/runtime": true 25 | }, 26 | "sort-packages": true 27 | }, 28 | "autoload": { 29 | "psr-4": { 30 | "App\\": "src/" 31 | } 32 | }, 33 | "autoload-dev": { 34 | "psr-4": { 35 | "App\\Tests\\": "tests/" 36 | } 37 | }, 38 | "replace": { 39 | "symfony/polyfill-ctype": "*", 40 | "symfony/polyfill-iconv": "*", 41 | "symfony/polyfill-php72": "*", 42 | "symfony/polyfill-php73": "*", 43 | "symfony/polyfill-php74": "*", 44 | "symfony/polyfill-php80": "*", 45 | "symfony/polyfill-php81": "*", 46 | "symfony/polyfill-php82": "*" 47 | }, 48 | "scripts": { 49 | "auto-scripts": { 50 | "cache:clear": "symfony-cmd", 51 | "assets:install %PUBLIC_DIR%": "symfony-cmd" 52 | }, 53 | "post-install-cmd": [ 54 | "@auto-scripts" 55 | ], 56 | "post-update-cmd": [ 57 | "@auto-scripts" 58 | ] 59 | }, 60 | "conflict": { 61 | "symfony/symfony": "*" 62 | }, 63 | "extra": { 64 | "symfony": { 65 | "allow-contrib": false, 66 | "require": "7.0.*" 67 | } 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /projects-php/php-tips/tip5/config/bundles.php: -------------------------------------------------------------------------------- 1 | ['all' => true], 5 | Symfony\Bundle\MakerBundle\MakerBundle::class => ['dev' => true], 6 | ]; 7 | -------------------------------------------------------------------------------- /projects-php/php-tips/tip5/config/packages/cache.yaml: -------------------------------------------------------------------------------- 1 | framework: 2 | cache: 3 | # Unique name of your app: used to compute stable namespaces for cache keys. 4 | #prefix_seed: your_vendor_name/app_name 5 | 6 | # The "app" cache stores to the filesystem by default. 7 | # The data in this cache should persist between deploys. 8 | # Other options include: 9 | 10 | # Redis 11 | #app: cache.adapter.redis 12 | #default_redis_provider: redis://localhost 13 | 14 | # APCu (not recommended with heavy random-write workloads as memory fragmentation can cause perf issues) 15 | #app: cache.adapter.apcu 16 | 17 | # Namespaced pools use the above "app" backend by default 18 | #pools: 19 | #my.dedicated.cache: null 20 | -------------------------------------------------------------------------------- /projects-php/php-tips/tip5/config/packages/framework.yaml: -------------------------------------------------------------------------------- 1 | # see https://symfony.com/doc/current/reference/configuration/framework.html 2 | framework: 3 | secret: '%env(APP_SECRET)%' 4 | #csrf_protection: true 5 | 6 | # Note that the session will be started ONLY if you read or write from it. 7 | session: true 8 | 9 | #esi: true 10 | #fragments: true 11 | 12 | when@test: 13 | framework: 14 | test: true 15 | session: 16 | storage_factory_id: session.storage.factory.mock_file 17 | -------------------------------------------------------------------------------- /projects-php/php-tips/tip5/config/packages/routing.yaml: -------------------------------------------------------------------------------- 1 | framework: 2 | router: 3 | # Configure how to generate URLs in non-HTTP contexts, such as CLI commands. 4 | # See https://symfony.com/doc/current/routing.html#generating-urls-in-commands 5 | #default_uri: http://localhost 6 | 7 | when@prod: 8 | framework: 9 | router: 10 | strict_requirements: null 11 | -------------------------------------------------------------------------------- /projects-php/php-tips/tip5/config/preload.php: -------------------------------------------------------------------------------- 1 | setHelp(file_get_contents(__DIR__ . '/NewClass.txt')); 28 | } 29 | 30 | public function generate(InputInterface $input, ConsoleStyle $io, Generator $generator): void 31 | { 32 | $generator->generateClass( 33 | 'App\Maker\NewClass', 34 | __DIR__ . '/NewClass.tpl.php' 35 | ); 36 | 37 | $generator->writeChanges(); 38 | $this->writeSuccessMessage($io); 39 | } 40 | 41 | public function configureDependencies(DependencyBuilder $dependencies): void 42 | { 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /projects-php/php-tips/tip5/src/Maker/NewClass.php: -------------------------------------------------------------------------------- 1 | 2 | 3 | namespace src\Maker; 4 | 5 | class NewClass { 6 | 7 | public function hello() { 8 | echo 'Hello World!'; 9 | } 10 | 11 | } -------------------------------------------------------------------------------- /projects-php/php-tips/tip5/src/Maker/NewClass.txt: -------------------------------------------------------------------------------- 1 | The %command.name% command generates a Class! -------------------------------------------------------------------------------- /projects-php/php-tips/tip5/symfony.lock: -------------------------------------------------------------------------------- 1 | { 2 | "symfony/console": { 3 | "version": "7.0", 4 | "recipe": { 5 | "repo": "github.com/symfony/recipes", 6 | "branch": "main", 7 | "version": "5.3", 8 | "ref": "1781ff40d8a17d87cf53f8d4cf0c8346ed2bb461" 9 | }, 10 | "files": [ 11 | "./bin/console" 12 | ] 13 | }, 14 | "symfony/flex": { 15 | "version": "2.4", 16 | "recipe": { 17 | "repo": "github.com/symfony/recipes", 18 | "branch": "main", 19 | "version": "1.0", 20 | "ref": "146251ae39e06a95be0fe3d13c807bcf3938b172" 21 | }, 22 | "files": [ 23 | "./.env" 24 | ] 25 | }, 26 | "symfony/framework-bundle": { 27 | "version": "7.0", 28 | "recipe": { 29 | "repo": "github.com/symfony/recipes", 30 | "branch": "main", 31 | "version": "7.0", 32 | "ref": "6356c19b9ae08e7763e4ba2d9ae63043efc75db5" 33 | }, 34 | "files": [ 35 | "./config/packages/cache.yaml", 36 | "./config/packages/framework.yaml", 37 | "./config/preload.php", 38 | "./config/routes/framework.yaml", 39 | "./config/services.yaml", 40 | "./public/index.php", 41 | "./src/Controller/.gitignore", 42 | "./src/Kernel.php" 43 | ] 44 | }, 45 | "symfony/maker-bundle": { 46 | "version": "1.57", 47 | "recipe": { 48 | "repo": "github.com/symfony/recipes", 49 | "branch": "main", 50 | "version": "1.0", 51 | "ref": "fadbfe33303a76e25cb63401050439aa9b1a9c7f" 52 | } 53 | }, 54 | "symfony/routing": { 55 | "version": "7.0", 56 | "recipe": { 57 | "repo": "github.com/symfony/recipes", 58 | "branch": "main", 59 | "version": "7.0", 60 | "ref": "21b72649d5622d8f7da329ffb5afb232a023619d" 61 | }, 62 | "files": [ 63 | "./config/packages/routing.yaml", 64 | "./config/routes.yaml" 65 | ] 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /projects-php/php-tips/vercel.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": 2, 3 | "builds": [ 4 | { 5 | "src": "api/**/*.php", 6 | "use": "@vercel/php" 7 | } 8 | ], 9 | "routes": [ 10 | { 11 | "src": "/(.*)", 12 | "dest": "/api/index.php" 13 | } 14 | ] 15 | } 16 | -------------------------------------------------------------------------------- /projects-php/php-todo/README.md: -------------------------------------------------------------------------------- 1 | # php-to-do 2 | 3 | -------------------------------------------------------------------------------- /projects-php/php-todo/assets/css/bootstrap-reboot.min.css: -------------------------------------------------------------------------------- 1 | /*! 2 | * Bootstrap Reboot v4.3.1 (https://getbootstrap.com/) 3 | * Copyright 2011-2019 The Bootstrap Authors 4 | * Copyright 2011-2019 Twitter, Inc. 5 | * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) 6 | * Forked from Normalize.css, licensed MIT (https://github.com/necolas/normalize.css/blob/master/LICENSE.md) 7 | */*,::after,::before{box-sizing:border-box}html{font-family:sans-serif;line-height:1.15;-webkit-text-size-adjust:100%;-webkit-tap-highlight-color:transparent}article,aside,figcaption,figure,footer,header,hgroup,main,nav,section{display:block}body{margin:0;font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,"Helvetica Neue",Arial,"Noto Sans",sans-serif,"Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol","Noto Color Emoji";font-size:1rem;font-weight:400;line-height:1.5;color:#212529;text-align:left;background-color:#fff}[tabindex="-1"]:focus{outline:0!important}hr{box-sizing:content-box;height:0;overflow:visible}h1,h2,h3,h4,h5,h6{margin-top:0;margin-bottom:.5rem}p{margin-top:0;margin-bottom:1rem}abbr[data-original-title],abbr[title]{text-decoration:underline;-webkit-text-decoration:underline dotted;text-decoration:underline dotted;cursor:help;border-bottom:0;-webkit-text-decoration-skip-ink:none;text-decoration-skip-ink:none}address{margin-bottom:1rem;font-style:normal;line-height:inherit}dl,ol,ul{margin-top:0;margin-bottom:1rem}ol ol,ol ul,ul ol,ul ul{margin-bottom:0}dt{font-weight:700}dd{margin-bottom:.5rem;margin-left:0}blockquote{margin:0 0 1rem}b,strong{font-weight:bolder}small{font-size:80%}sub,sup{position:relative;font-size:75%;line-height:0;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}a{color:#007bff;text-decoration:none;background-color:transparent}a:hover{color:#0056b3;text-decoration:underline}a:not([href]):not([tabindex]){color:inherit;text-decoration:none}a:not([href]):not([tabindex]):focus,a:not([href]):not([tabindex]):hover{color:inherit;text-decoration:none}a:not([href]):not([tabindex]):focus{outline:0}code,kbd,pre,samp{font-family:SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace;font-size:1em}pre{margin-top:0;margin-bottom:1rem;overflow:auto}figure{margin:0 0 1rem}img{vertical-align:middle;border-style:none}svg{overflow:hidden;vertical-align:middle}table{border-collapse:collapse}caption{padding-top:.75rem;padding-bottom:.75rem;color:#6c757d;text-align:left;caption-side:bottom}th{text-align:inherit}label{display:inline-block;margin-bottom:.5rem}button{border-radius:0}button:focus{outline:1px dotted;outline:5px auto -webkit-focus-ring-color}button,input,optgroup,select,textarea{margin:0;font-family:inherit;font-size:inherit;line-height:inherit}button,input{overflow:visible}button,select{text-transform:none}select{word-wrap:normal}[type=button],[type=reset],[type=submit],button{-webkit-appearance:button}[type=button]:not(:disabled),[type=reset]:not(:disabled),[type=submit]:not(:disabled),button:not(:disabled){cursor:pointer}[type=button]::-moz-focus-inner,[type=reset]::-moz-focus-inner,[type=submit]::-moz-focus-inner,button::-moz-focus-inner{padding:0;border-style:none}input[type=checkbox],input[type=radio]{box-sizing:border-box;padding:0}input[type=date],input[type=datetime-local],input[type=month],input[type=time]{-webkit-appearance:listbox}textarea{overflow:auto;resize:vertical}fieldset{min-width:0;padding:0;margin:0;border:0}legend{display:block;width:100%;max-width:100%;padding:0;margin-bottom:.5rem;font-size:1.5rem;line-height:inherit;color:inherit;white-space:normal}progress{vertical-align:baseline}[type=number]::-webkit-inner-spin-button,[type=number]::-webkit-outer-spin-button{height:auto}[type=search]{outline-offset:-2px;-webkit-appearance:none}[type=search]::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{font:inherit;-webkit-appearance:button}output{display:inline-block}summary{display:list-item;cursor:pointer}template{display:none}[hidden]{display:none!important} 8 | /*# sourceMappingURL=bootstrap-reboot.min.css.map */ -------------------------------------------------------------------------------- /projects-php/php-todo/assets/images/fav/android-icon-144x144.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RazielRodrigues/php-projects/551e08b0b6aafea510a004dab9268b88c1b627f7/projects-php/php-todo/assets/images/fav/android-icon-144x144.png -------------------------------------------------------------------------------- /projects-php/php-todo/assets/images/fav/android-icon-192x192.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RazielRodrigues/php-projects/551e08b0b6aafea510a004dab9268b88c1b627f7/projects-php/php-todo/assets/images/fav/android-icon-192x192.png -------------------------------------------------------------------------------- /projects-php/php-todo/assets/images/fav/android-icon-36x36.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RazielRodrigues/php-projects/551e08b0b6aafea510a004dab9268b88c1b627f7/projects-php/php-todo/assets/images/fav/android-icon-36x36.png -------------------------------------------------------------------------------- /projects-php/php-todo/assets/images/fav/android-icon-48x48.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RazielRodrigues/php-projects/551e08b0b6aafea510a004dab9268b88c1b627f7/projects-php/php-todo/assets/images/fav/android-icon-48x48.png -------------------------------------------------------------------------------- /projects-php/php-todo/assets/images/fav/android-icon-72x72.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RazielRodrigues/php-projects/551e08b0b6aafea510a004dab9268b88c1b627f7/projects-php/php-todo/assets/images/fav/android-icon-72x72.png -------------------------------------------------------------------------------- /projects-php/php-todo/assets/images/fav/android-icon-96x96.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RazielRodrigues/php-projects/551e08b0b6aafea510a004dab9268b88c1b627f7/projects-php/php-todo/assets/images/fav/android-icon-96x96.png -------------------------------------------------------------------------------- /projects-php/php-todo/assets/images/fav/apple-icon-114x114.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RazielRodrigues/php-projects/551e08b0b6aafea510a004dab9268b88c1b627f7/projects-php/php-todo/assets/images/fav/apple-icon-114x114.png -------------------------------------------------------------------------------- /projects-php/php-todo/assets/images/fav/apple-icon-120x120.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RazielRodrigues/php-projects/551e08b0b6aafea510a004dab9268b88c1b627f7/projects-php/php-todo/assets/images/fav/apple-icon-120x120.png -------------------------------------------------------------------------------- /projects-php/php-todo/assets/images/fav/apple-icon-144x144.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RazielRodrigues/php-projects/551e08b0b6aafea510a004dab9268b88c1b627f7/projects-php/php-todo/assets/images/fav/apple-icon-144x144.png -------------------------------------------------------------------------------- /projects-php/php-todo/assets/images/fav/apple-icon-152x152.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RazielRodrigues/php-projects/551e08b0b6aafea510a004dab9268b88c1b627f7/projects-php/php-todo/assets/images/fav/apple-icon-152x152.png -------------------------------------------------------------------------------- /projects-php/php-todo/assets/images/fav/apple-icon-180x180.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RazielRodrigues/php-projects/551e08b0b6aafea510a004dab9268b88c1b627f7/projects-php/php-todo/assets/images/fav/apple-icon-180x180.png -------------------------------------------------------------------------------- /projects-php/php-todo/assets/images/fav/apple-icon-57x57.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RazielRodrigues/php-projects/551e08b0b6aafea510a004dab9268b88c1b627f7/projects-php/php-todo/assets/images/fav/apple-icon-57x57.png -------------------------------------------------------------------------------- /projects-php/php-todo/assets/images/fav/apple-icon-60x60.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RazielRodrigues/php-projects/551e08b0b6aafea510a004dab9268b88c1b627f7/projects-php/php-todo/assets/images/fav/apple-icon-60x60.png -------------------------------------------------------------------------------- /projects-php/php-todo/assets/images/fav/apple-icon-72x72.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RazielRodrigues/php-projects/551e08b0b6aafea510a004dab9268b88c1b627f7/projects-php/php-todo/assets/images/fav/apple-icon-72x72.png -------------------------------------------------------------------------------- /projects-php/php-todo/assets/images/fav/apple-icon-76x76.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RazielRodrigues/php-projects/551e08b0b6aafea510a004dab9268b88c1b627f7/projects-php/php-todo/assets/images/fav/apple-icon-76x76.png -------------------------------------------------------------------------------- /projects-php/php-todo/assets/images/fav/apple-icon-precomposed.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RazielRodrigues/php-projects/551e08b0b6aafea510a004dab9268b88c1b627f7/projects-php/php-todo/assets/images/fav/apple-icon-precomposed.png -------------------------------------------------------------------------------- /projects-php/php-todo/assets/images/fav/apple-icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RazielRodrigues/php-projects/551e08b0b6aafea510a004dab9268b88c1b627f7/projects-php/php-todo/assets/images/fav/apple-icon.png -------------------------------------------------------------------------------- /projects-php/php-todo/assets/images/fav/browserconfig.xml: -------------------------------------------------------------------------------- 1 | 2 | #ffffff -------------------------------------------------------------------------------- /projects-php/php-todo/assets/images/fav/favicon-16x16.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RazielRodrigues/php-projects/551e08b0b6aafea510a004dab9268b88c1b627f7/projects-php/php-todo/assets/images/fav/favicon-16x16.png -------------------------------------------------------------------------------- /projects-php/php-todo/assets/images/fav/favicon-32x32.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RazielRodrigues/php-projects/551e08b0b6aafea510a004dab9268b88c1b627f7/projects-php/php-todo/assets/images/fav/favicon-32x32.png -------------------------------------------------------------------------------- /projects-php/php-todo/assets/images/fav/favicon-96x96.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RazielRodrigues/php-projects/551e08b0b6aafea510a004dab9268b88c1b627f7/projects-php/php-todo/assets/images/fav/favicon-96x96.png -------------------------------------------------------------------------------- /projects-php/php-todo/assets/images/fav/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RazielRodrigues/php-projects/551e08b0b6aafea510a004dab9268b88c1b627f7/projects-php/php-todo/assets/images/fav/favicon.ico -------------------------------------------------------------------------------- /projects-php/php-todo/assets/images/fav/manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "App", 3 | "icons": [ 4 | { 5 | "src": "\/android-icon-36x36.png", 6 | "sizes": "36x36", 7 | "type": "image\/png", 8 | "density": "0.75" 9 | }, 10 | { 11 | "src": "\/android-icon-48x48.png", 12 | "sizes": "48x48", 13 | "type": "image\/png", 14 | "density": "1.0" 15 | }, 16 | { 17 | "src": "\/android-icon-72x72.png", 18 | "sizes": "72x72", 19 | "type": "image\/png", 20 | "density": "1.5" 21 | }, 22 | { 23 | "src": "\/android-icon-96x96.png", 24 | "sizes": "96x96", 25 | "type": "image\/png", 26 | "density": "2.0" 27 | }, 28 | { 29 | "src": "\/android-icon-144x144.png", 30 | "sizes": "144x144", 31 | "type": "image\/png", 32 | "density": "3.0" 33 | }, 34 | { 35 | "src": "\/android-icon-192x192.png", 36 | "sizes": "192x192", 37 | "type": "image\/png", 38 | "density": "4.0" 39 | } 40 | ] 41 | } -------------------------------------------------------------------------------- /projects-php/php-todo/assets/images/fav/ms-icon-144x144.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RazielRodrigues/php-projects/551e08b0b6aafea510a004dab9268b88c1b627f7/projects-php/php-todo/assets/images/fav/ms-icon-144x144.png -------------------------------------------------------------------------------- /projects-php/php-todo/assets/images/fav/ms-icon-150x150.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RazielRodrigues/php-projects/551e08b0b6aafea510a004dab9268b88c1b627f7/projects-php/php-todo/assets/images/fav/ms-icon-150x150.png -------------------------------------------------------------------------------- /projects-php/php-todo/assets/images/fav/ms-icon-310x310.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RazielRodrigues/php-projects/551e08b0b6aafea510a004dab9268b88c1b627f7/projects-php/php-todo/assets/images/fav/ms-icon-310x310.png -------------------------------------------------------------------------------- /projects-php/php-todo/assets/images/fav/ms-icon-70x70.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RazielRodrigues/php-projects/551e08b0b6aafea510a004dab9268b88c1b627f7/projects-php/php-todo/assets/images/fav/ms-icon-70x70.png -------------------------------------------------------------------------------- /projects-php/php-todo/assets/sql/database.sql: -------------------------------------------------------------------------------- 1 | CREATE TABLE ANOTACAO( 2 | ID_ANOTACAO INTEGER AUTO_INCREMENT PRIMARY KEY, 3 | CONTEUDO TEXT NOT NULL 4 | ); -------------------------------------------------------------------------------- /projects-php/php-todo/assets/sql/queries.php: -------------------------------------------------------------------------------- 1 | Ops! erro de conexao" . $conexao->connect_error . ""); 15 | } 16 | 17 | 18 | if (!$conexao) { 19 | die("

Ops! erro de conexao

" . $conexao->connect_error); 20 | } 21 | 22 | $queryAlter = " ALTER TABLE `anotacao` CHANGE `conteudo` `conteudo` TEXT CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL; 23 | "; 24 | 25 | $queryInsert = "INSERT INTO anotacao(id_anotacao, conteudo) 26 | VALUES(default,'oi')"; 27 | 28 | // verificando se deu certo o SQL 29 | if ($conexao->query($query) === TRUE) { 30 | echo "SQL Executado!"; 31 | } else { 32 | echo "Error: " . $query . "
" . $conexao->error; 33 | } 34 | 35 | $querySelect = "SELECT * FROM anotacao"; 36 | $resultadoSelect = $conexao->query($querySelect); 37 | 38 | 39 | if ($resultadoSelect->num_rows > 0) { 40 | echo ""; 45 | }else{ 46 | echo "Sem resultados"; 47 | } 48 | 49 | 50 | 51 | 52 | 53 | 54 | $queryDelete = "DELETE FROM anotacao WHERE id_anotacao = 2"; 55 | 56 | if (mysqli_query($conexao,$queryDelete)) { 57 | echo "Deletado com sucesso"; 58 | }else{ 59 | echo "ERRO NA HORA DE DELETAR". mysqli_error($conexao); 60 | } 61 | 62 | 63 | 64 | 65 | $queryUpdate = "UPDATE anotacao SET conteudo ='mudei o conteudo' WHERE id_anotacao = 1"; 66 | 67 | if (mysqli_query($conexao,$queryUpdate)) { 68 | echo "update efetuado"; 69 | }else{ 70 | echo "update errado"; 71 | } 72 | 73 | 74 | 75 | 76 | mysqli_close($conexao); 77 | ?> -------------------------------------------------------------------------------- /projects-php/php-todo/index.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /projects-php/php-todo/model/apagar_anotacao.php: -------------------------------------------------------------------------------- 1 | ERRO NA HORA DE DELETAR: ". mysqli_error($conexao).""; 14 | } 15 | 16 | mysqli_query($conexao, $queryDeletar); -------------------------------------------------------------------------------- /projects-php/php-todo/model/atualizar_anotacao.php: -------------------------------------------------------------------------------- 1 | ERRO NA HORA DE DELETAR: ". mysqli_error($conexao).""; 15 | } -------------------------------------------------------------------------------- /projects-php/php-todo/model/database.php: -------------------------------------------------------------------------------- 1 | Ops! erro de conexao" . $conexao->connect_error . ""); 15 | } 16 | -------------------------------------------------------------------------------- /projects-php/php-todo/model/inserir_anotacao.php: -------------------------------------------------------------------------------- 1 | 2 |
3 |
4 | 5 |
6 |
7 |
8 | 22 |
23 | 24 |
25 |
26 | -------------------------------------------------------------------------------- /projects-php/php-todo/views/footer.php: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /projects-php/php-todo/views/header.php: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | TO-DO 28 | 29 | 30 | -------------------------------------------------------------------------------- /projects-php/php-todo/views/home.php: -------------------------------------------------------------------------------- 1 |
2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | query($querySelect); 14 | if ($resultadoSelect->num_rows > 0) { 15 | while ($row = $resultadoSelect->fetch_assoc()) { 16 | echo ""; 17 | echo ""; 18 | echo ""; 19 | echo ""; 20 | } 21 | }else{ 22 | echo ""; 23 | echo ""; 24 | } 25 | ?> 26 | 27 | 28 |
Conteudo
".$row["ID_ANOTACAO"]."".$row["CONTEUDO"]."
0Sem resultados
29 |
-------------------------------------------------------------------------------- /projects-php/php-todo/views/inserir.php: -------------------------------------------------------------------------------- 1 |
2 |
3 |
4 | 5 |
6 | 7 |
8 |
9 |
10 | 11 |
12 |
13 | 27 |
28 | 29 |
30 |
31 |
-------------------------------------------------------------------------------- /projects-php/php-unit-tests/.vscode/launch.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "0.2.0", 3 | "configurations": [ 4 | { 5 | "name": "Listen for XDebug on Docker", 6 | "type": "php", 7 | "request": "launch", 8 | "port": 9005, 9 | "pathMappings": { 10 | "/var/www/html/": "${workspaceFolder}" 11 | } 12 | } 13 | ] 14 | } 15 | -------------------------------------------------------------------------------- /projects-php/php-unit-tests/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM php:7.2-apache 2 | 3 | # Instalação do SQLite e PDO SQLite 4 | RUN apt-get update && \ 5 | apt-get install -y libsqlite3-dev && \ 6 | docker-php-ext-install pdo_sqlite 7 | 8 | # Instalação do driver MySQLi 9 | RUN docker-php-ext-install mysqli 10 | 11 | # Instalação do Xdebug 12 | RUN pecl install xdebug-2.7.0 && docker-php-ext-enable xdebug 13 | COPY ./docker/php/conf.d/xdebug.ini /usr/local/etc/php/conf.d/docker-php-ext-xdebug.ini 14 | COPY ./docker/php/conf.d/error_reporting.ini /usr/local/etc/php/conf.d/error_reporting.ini 15 | 16 | 17 | # Instalação do Composer 18 | RUN curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/local/bin --filename=composer 19 | 20 | # Limpeza de pacotes não necessários 21 | RUN apt-get clean && \ 22 | rm -rf /var/lib/apt/lists/* 23 | -------------------------------------------------------------------------------- /projects-php/php-unit-tests/README.md: -------------------------------------------------------------------------------- 1 | # PHP UNIT STUDIES 2 | 3 | PHPUnit is a test runner for PHP with it you can write simple and useful test cases for your code. 4 | 5 | 6 | 7 | 8 | 9 | 10 | # NOTES 11 | 12 | - install php unit 13 | - composer install phpunit 14 | - create files with test and methods 15 | - run with vendor/bin/phpunit tests 16 | - here you can filter with --filter="FileTest.php" 17 | - with data providers: --filter=testTotal#1 (will run the first index) 18 | - adds the phpunit.xml config file 19 | - configure styles 20 | - configure testsuits (test a whole file or folder) 21 | 22 | # HOW TO TEST 23 | 24 | - use assert functions 25 | - use setUp and tearDown for one instance methods 26 | - follow TDD principle: arrange , act and assert 27 | 28 | # TEST DOUBLE 29 | 30 | Ability to test your code such as databases without production data or objects those strategy are: 31 | - Dummy: one object that haven't real data 32 | - Fake: a fake class that you need to pass 33 | - Stub: change original function execution 34 | - Spy: See how many times a function were called 35 | - Mock: a fake object for a input 36 | 37 | # TECH STACK 38 | 39 | - PHP 7.2 40 | - DOCKER 41 | - PHPUNIT 42 | - COMPOSER 43 | 44 | # REFERENCES: 45 | - https://www.linkedin.com/learning/php-test-driven-development-with-phpunit 46 | - https://phpunit.de/documentation.html 47 | 48 | 49 | PHP Test Driven Development 50 | https://www.linkedin.com/learning/certificates/975e8272c338a59fe814b0bc860be83f13199004ac5e3100234df0dcce98c713 -------------------------------------------------------------------------------- /projects-php/php-unit-tests/app/.gitignore: -------------------------------------------------------------------------------- 1 | /vendor -------------------------------------------------------------------------------- /projects-php/php-unit-tests/app/composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "require-dev": { 3 | "phpunit/phpunit": "^5.5" 4 | }, 5 | "autoload": { 6 | "psr-4": { 7 | "TDD\\": "src/" 8 | } 9 | }, 10 | "autoload-dev": { 11 | "psr-4": { 12 | "TDD\\Test\\": "test/" 13 | } 14 | } 15 | } -------------------------------------------------------------------------------- /projects-php/php-unit-tests/app/phpunit.xml: -------------------------------------------------------------------------------- 1 | 2 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | ./tests 17 | 18 | 19 | ./tests 20 | ./tests/ReceiptItems.php 21 | 22 | 23 | 24 | 25 | 35 | 36 | ./src 37 | 44 | 45 | 46 | 62 | 63 | -------------------------------------------------------------------------------- /projects-php/php-unit-tests/app/src/CalculatorService.php: -------------------------------------------------------------------------------- 1 | printCalculationService->array($result); 34 | } 35 | 36 | if ($type === 'print') { 37 | return $this->printCalculationService->print($result); 38 | } 39 | 40 | throw new \Exception("Error Processing Request", 1); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /projects-php/php-unit-tests/app/src/Formatter.php: -------------------------------------------------------------------------------- 1 | PDO = $pdo; 16 | } 17 | 18 | public function __destruct() 19 | { 20 | unset($this->PDO); 21 | } 22 | 23 | public function findForId($id) 24 | { 25 | $query = "SELECT * FROM {$this->table} WHERE {$this->table}.id = ?"; 26 | $statement = $this->PDO->prepare($query); 27 | $statement->execute([$id]); 28 | return $statement->fetch(PDO::FETCH_ASSOC); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /projects-php/php-unit-tests/app/src/PrintCalculationService.php: -------------------------------------------------------------------------------- 1 | $result 17 | ]; 18 | } 19 | 20 | function print(int $result): string 21 | { 22 | 23 | # a lot of business rules... 24 | 25 | return 'result: ' . $result; 26 | } 27 | 28 | } 29 | -------------------------------------------------------------------------------- /projects-php/php-unit-tests/app/src/Receipt.php: -------------------------------------------------------------------------------- 1 | Formatter = $formatter; 14 | } 15 | 16 | public function subTotal(array $items = [], $coupun) 17 | { 18 | $sum = array_sum($items); 19 | if (!is_null($coupun)) { 20 | 21 | if ($coupun > 1.00) { 22 | throw new \BadMethodCallException("Must be lower than 1.00 or equal"); 23 | } 24 | 25 | return $sum - ($sum * $coupun); 26 | } 27 | return $sum; 28 | } 29 | 30 | public function tax($amount) 31 | { 32 | return $this->Formatter->currencyAmt($amount * $this->tax); 33 | } 34 | 35 | public function postTaxSubTotal($valores, $coupun) 36 | { 37 | $subtotal = $this->subTotal($valores, $coupun); 38 | return $subtotal + $this->tax($subtotal, $this->tax); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /projects-php/php-unit-tests/app/src/index.php: -------------------------------------------------------------------------------- 1 | subTotal([1, 20, 25], null); 12 | 13 | 14 | 15 | var_dump($receipts); 16 | -------------------------------------------------------------------------------- /projects-php/php-unit-tests/app/tests/CalculatorServiceTest.php: -------------------------------------------------------------------------------- 1 | printCalculationService = $this->createMock(PrintCalculationService::class); 21 | } 22 | 23 | protected function tearDown(): void 24 | { 25 | $this->printCalculationService = null; 26 | } 27 | 28 | static function sumProvider() { 29 | yield [10, 10, 20]; 30 | yield [1, 1, 2]; 31 | yield [2, 2, 4]; 32 | } 33 | 34 | #[Test] 35 | #[DataProvider('sumProvider')] 36 | function testSum($x, $y, $expected) { 37 | $service = new CalculatorService(); 38 | $this->assertSame( 39 | $service->sum($x,$y), 40 | $expected 41 | ); 42 | } 43 | 44 | #[Test] 45 | function testDivision() { 46 | $service = new CalculatorService(); 47 | $this->assertEquals( 48 | $service->division(10,10), 49 | 1 50 | ); 51 | } 52 | 53 | #[Test] 54 | function testDivisionException() { 55 | $this->expectException(\Exception::class); 56 | 57 | $service = new CalculatorService(); 58 | $this->assertSame( 59 | $service->division(0,10), 60 | 1 61 | ); 62 | } 63 | 64 | #[Test] 65 | function testDivisionExceptionInvalid() { 66 | $this->markTestIncomplete('...'); 67 | } 68 | 69 | #[Test] 70 | function testSumPrint() { 71 | $service = new CalculatorService($this->printCalculationService); 72 | $result = $service->sum(1,1); 73 | $this->assertSame( 74 | $result, 75 | 2 76 | ); 77 | 78 | $this->printCalculationService->method('array')->willReturn([ 79 | 'result mock: 2' 80 | ]); 81 | 82 | $print = $service->show($result, 'array'); 83 | $this->assertSame( 84 | $print, 85 | [ 86 | 'result mock: 2' 87 | ] 88 | ); 89 | 90 | $this->printCalculationService->method('print')->willReturn( 91 | 'result mock: 2' 92 | ); 93 | 94 | $print = $service->show($result, 'print'); 95 | $this->assertSame( 96 | $print, 97 | 'result mock: 2' 98 | ); 99 | 100 | } 101 | 102 | } 103 | -------------------------------------------------------------------------------- /projects-php/php-unit-tests/app/tests/FormatterTest.php: -------------------------------------------------------------------------------- 1 | Formatter = new Formatter(); 19 | } 20 | 21 | public function tearDown() 22 | { 23 | unset($this->Formatter); 24 | } 25 | 26 | /** 27 | * @dataProvider provideCurrencyAmt 28 | */ 29 | public function testCurrencyAmt($expected, $input, $msg) 30 | { 31 | $this->assertSame( 32 | $expected, 33 | $this->Formatter->currencyAmt($input), 34 | $msg 35 | ); 36 | } 37 | 38 | public function provideCurrencyAmt() 39 | { 40 | return [ 41 | [1.00, 1, "should be 1.00"], 42 | [1.11, 1.111, "should be 1.11"], 43 | [1.22, 1.22222, "should be 1.22"] 44 | ]; 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /projects-php/php-unit-tests/app/tests/ItemsTableTest.php: -------------------------------------------------------------------------------- 1 | PDO = $this->getConnection(); 17 | $this->createTable(); 18 | $this->populateTable(); 19 | 20 | $this->ItemsTable = new ItemsTable($this->PDO); 21 | } 22 | 23 | public function tearDown() 24 | { 25 | unset($this->ItemsTable); 26 | unset($this->PDO); 27 | } 28 | 29 | public function testFindForId() 30 | { 31 | $id = 1; 32 | 33 | $result = $this->ItemsTable->findForId($id); 34 | $this->assertInternalType( 35 | 'array', 36 | $result, 37 | 'The result should always be an array.' 38 | ); 39 | $this->assertEquals( 40 | $id, 41 | $result['id'], 42 | 'The id key/value of the result for id should be equal to the id.' 43 | ); 44 | $this->assertEquals( 45 | 'Candy', 46 | $result['name'], 47 | 'The id key/value of the result for name should be equal to `Candy`.' 48 | ); 49 | } 50 | 51 | public function testFindForIdMock() 52 | { 53 | $id = 1; 54 | 55 | $PDOStatement = $this->getMockBuilder('\PDOStatement') 56 | ->setMethods(['execute', 'fetch']) 57 | ->getMock(); 58 | 59 | $PDOStatement->expects($this->once()) 60 | ->method('execute') 61 | ->with([$id]) 62 | ->will($this->returnSelf()); 63 | $PDOStatement->expects($this->once()) 64 | ->method('fetch') 65 | ->with($this->anything()) 66 | ->will($this->returnValue('canary')); 67 | 68 | $PDO = $this->getMockBuilder('\PDO') 69 | ->setMethods(['prepare']) 70 | ->disableOriginalConstructor() 71 | ->getMock(); 72 | 73 | $PDO->expects($this->once()) 74 | ->method('prepare') 75 | ->with($this->stringContains('SELECT * FROM')) 76 | ->willReturn($PDOStatement); 77 | 78 | $ItemsTable = new ItemsTable($PDO); 79 | 80 | $output = $ItemsTable->findForId($id); 81 | 82 | $this->assertEquals( 83 | 'canary', 84 | $output, 85 | 'The output for the mocked instance of the PDO and PDOStatment should produce the string `canary`.' 86 | ); 87 | } 88 | 89 | protected function getConnection() 90 | { 91 | return new PDO('sqlite::memory:'); 92 | } 93 | 94 | protected function createTable() 95 | { 96 | $query = " 97 | CREATE TABLE `items` ( 98 | `id` INTEGER, 99 | `name` TEXT, 100 | `price` REAL, 101 | PRIMARY KEY(`id`) 102 | ); 103 | "; 104 | $this->PDO->query($query); 105 | } 106 | 107 | protected function populateTable() 108 | { 109 | $query = " 110 | INSERT INTO `items` VALUES (1,'Candy',1.00); 111 | INSERT INTO `items` VALUES (2,'TShirt',5.34); 112 | "; 113 | $this->PDO->query($query); 114 | } 115 | } 116 | -------------------------------------------------------------------------------- /projects-php/php-unit-tests/app/tests/ReceiptTest.php: -------------------------------------------------------------------------------- 1 | Formatter = $this->getMockBuilder('TDD\Formatter') 21 | ->setMethods(['currencyAmt']) 22 | ->getMock(); 23 | $this->Formatter->expects($this->any()) 24 | ->method('currencyAmt') 25 | ->with($this->anything()) 26 | ->will($this->returnArgument(0)); 27 | $this->Receipt = new Receipt($this->Formatter); 28 | } 29 | 30 | public function tearDown() 31 | { 32 | unset($this->Receipt); 33 | } 34 | 35 | /** 36 | * @dataProvider provideSubTotal 37 | */ 38 | public function testSubTotal($items, $expected) 39 | { 40 | $output = $this->Receipt->subTotal($items, null); 41 | $this->assertEquals( 42 | $expected, 43 | $output, 44 | "When summing the subTotal should equal {$expected}" 45 | ); 46 | } 47 | 48 | public function provideSubTotal() 49 | { 50 | return [ 51 | [[2, 3, 4], 9], 52 | [[2, 3, 5], 10], 53 | [[-2, 3, 4], 5], 54 | ]; 55 | } 56 | 57 | public function testSubTotalAndCoupun() 58 | { 59 | $input = [0, 2, 5, 8]; 60 | $coupun = 0.20; 61 | $output = $this->Receipt->subTotal($input, $coupun); 62 | $this->assertEquals( 63 | 12, 64 | $output, 65 | 'When summing the subTotal should equal 15' 66 | ); 67 | } 68 | public function testSubTotalAndCoupunException() 69 | { 70 | $input = [0, 2, 5, 8]; 71 | $coupun = 1.20; 72 | $this->expectException('BadMethodCallException'); 73 | $this->Receipt->subTotal($input, $coupun); 74 | } 75 | 76 | public function testTax() 77 | { 78 | $inputAmount = 10.00; 79 | $this->Receipt->tax = 0.10; 80 | $output = $this->Receipt->tax($inputAmount); 81 | $this->assertEquals( 82 | 1.00, 83 | $output, 84 | 'The tax calculation should equal 1.00' 85 | ); 86 | } 87 | 88 | public function testPostTaxSubTotal() 89 | { 90 | 91 | $item = [1, 2, 5, 8]; 92 | $this->Receipt->tax = 0.20; 93 | 94 | $coupun = null; 95 | $Receipt = $this->getMockBuilder('TDD\Receipt') 96 | ->setMethods(['tax', 'subTotal']) 97 | ->setConstructorArgs([$this->Formatter]) 98 | ->getMock(); 99 | $Receipt->expects($this->once())->method('tax')->with(10)->willReturn(1.0); 100 | $Receipt->expects($this->once())->method('subTotal')->with($item, $coupun)->willReturn(10.00); 101 | $return = $Receipt->postTaxSubTotal([1, 2, 5, 8], null); 102 | $this->assertEquals( 103 | 11.00, 104 | $return 105 | ); 106 | } 107 | } 108 | -------------------------------------------------------------------------------- /projects-php/php-unit-tests/certificate-debug.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RazielRodrigues/php-projects/551e08b0b6aafea510a004dab9268b88c1b627f7/projects-php/php-unit-tests/certificate-debug.png -------------------------------------------------------------------------------- /projects-php/php-unit-tests/certificate.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RazielRodrigues/php-projects/551e08b0b6aafea510a004dab9268b88c1b627f7/projects-php/php-unit-tests/certificate.png -------------------------------------------------------------------------------- /projects-php/php-unit-tests/debugs.md: -------------------------------------------------------------------------------- 1 | # PHP DEBUGGING TECHNIQUES 2 | 3 | - common erros Notice, Warning, Fatal 4 | - debug_backtraces() 5 | - trigger_error() 6 | - set_error_handler() 7 | - var_dump, var_export and print_r 8 | - debug with cli 9 | - debugbar php legacy code 10 | - Ray dump debugging 11 | - Whoops 12 | - papertrail 13 | - sentry 14 | - new relic 15 | - datadog 16 | - monolog -------------------------------------------------------------------------------- /projects-php/php-unit-tests/docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: '3' 2 | 3 | services: 4 | php: 5 | build: . 6 | ports: 7 | - "80:80" 8 | volumes: 9 | - ./app:/var/www/html 10 | -------------------------------------------------------------------------------- /projects-php/php-unit-tests/testes.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RazielRodrigues/php-projects/551e08b0b6aafea510a004dab9268b88c1b627f7/projects-php/php-unit-tests/testes.png -------------------------------------------------------------------------------- /projects-php/php-zend-certification/.gitignore: -------------------------------------------------------------------------------- 1 | /zend -------------------------------------------------------------------------------- /projects-php/php-zend-certification/Behavorial/Flyweight.php: -------------------------------------------------------------------------------- 1 | flyweight[$tag])) { 20 | $this->flyweight[$tag] = new Storage($tag); 21 | 22 | return $this->flyweight[$tag]; 23 | } 24 | 25 | return $this->flyweight[$tag]; 26 | } 27 | } 28 | 29 | $factory = new StorageFlyweightFactory(); 30 | 31 | echo $factory->create('Raziel')->tag; 32 | echo $factory->create('Jaiara')->tag; 33 | echo $factory->create('Lisa')->tag; 34 | echo $factory->create('Sergio')->tag; 35 | 36 | echo $factory->create('Raziel')->tag; 37 | echo $factory->create('Jaiara')->tag; 38 | echo $factory->create('Lisa')->tag; 39 | echo $factory->create('Sergio')->tag; 40 | 41 | # Three objects, but called six times! 42 | var_dump($factory->flyweight); 43 | 44 | # Difference is minimal this scenario, but imagine with big objects! 45 | echo memory_get_peak_usage(); 46 | -------------------------------------------------------------------------------- /projects-php/php-zend-certification/Behavorial/Iterator.php: -------------------------------------------------------------------------------- 1 | $content]); 16 | } 17 | } 18 | 19 | class FormatArray implements FormatStategy 20 | { 21 | public function render(mixed $content): string 22 | { 23 | return print_r([$content => $content], true); 24 | } 25 | } 26 | 27 | # Using polymorphism 28 | class FormatPolymorphism 29 | { 30 | 31 | public function format(string $content, FormatStategy $format): void 32 | { 33 | echo $format->render($content); 34 | } 35 | } 36 | 37 | (new FormatPolymorphism())->format('Raziel...', new FormatArray()); 38 | (new FormatPolymorphism())->format('Raziel...', new FormatJson); 39 | 40 | # Delegating for a structure of control 41 | class FormatDelegating 42 | { 43 | 44 | public function format(string $content, string $format): void 45 | { 46 | echo match ($format) { 47 | 'json' => (new FormatJson)->render($content), 48 | 'array' => (new FormatArray)->render($content), 49 | }; 50 | } 51 | } 52 | 53 | (new FormatDelegating())->format('Raziel...', 'json'); 54 | (new FormatDelegating())->format('Raziel...', 'array'); 55 | -------------------------------------------------------------------------------- /projects-php/php-zend-certification/Behavorial/Visitor.php: -------------------------------------------------------------------------------- 1 | id = $id; 14 | return $this; 15 | } 16 | 17 | 18 | public function setFirstName(string $firstName): UserBuilder 19 | { 20 | $this->firstName = $firstName; 21 | return $this; 22 | } 23 | 24 | public function build(): array 25 | { 26 | return array( 27 | 'id' => $this->id, 28 | 'first_name' => $this->firstName 29 | ); 30 | } 31 | } 32 | 33 | # $user = new UserBuilder; 34 | # $user->setId(1); 35 | # $user->setFirstName('Raziel Rodrigues'); 36 | # print_r($user->build()); -------------------------------------------------------------------------------- /projects-php/php-zend-certification/Creational/Factory.php: -------------------------------------------------------------------------------- 1 | setId($this->id) 26 | ->setFirstName($this->firstName); 27 | } 28 | } 29 | 30 | for ($i = 1; $i < 10; $i++) { 31 | $user = new UserFactory($i, 'Raziel Rodrigues');; 32 | # print_r($user->get($i)->build()); 33 | } 34 | -------------------------------------------------------------------------------- /projects-php/php-zend-certification/InversionControl/DependencyInjection.php: -------------------------------------------------------------------------------- 1 | calculate(2, 3); 33 | } 34 | } 35 | 36 | class DependecyInjection 37 | { 38 | 39 | public function __construct(public Calculation $sum) 40 | { 41 | } 42 | 43 | public function get() 44 | { 45 | return $this->sum->calculate(2, 3); 46 | } 47 | } 48 | 49 | 50 | echo (new NoDependecyInjection())->get() . PHP_EOL; 51 | 52 | echo (new DependecyInjection(new Sum))->get() . PHP_EOL; 53 | 54 | echo (new DependecyInjection(new Minus))->get() . PHP_EOL; 55 | -------------------------------------------------------------------------------- /projects-php/php-zend-certification/InversionControl/ServiceLocator.php: -------------------------------------------------------------------------------- 1 | new Sum(), 27 | 'minus' => new Minus(), 28 | }; 29 | } 30 | } 31 | 32 | class Main 33 | { 34 | 35 | public function __construct(public ServiceLocator $serviceLocator) 36 | { 37 | } 38 | 39 | public function run($name) 40 | { 41 | $service = $this->serviceLocator->get($name); 42 | return $service->calculate(10, 2); 43 | } 44 | } 45 | 46 | 47 | echo (new Main(new ServiceLocator))->run('sum') . PHP_EOL; 48 | echo (new Main(new ServiceLocator))->run('minus') . PHP_EOL; 49 | -------------------------------------------------------------------------------- /projects-php/php-zend-certification/Structural/Adapter.php: -------------------------------------------------------------------------------- 1 | emailService = $emailService; 37 | } 38 | 39 | 40 | public function send(string $to, string $subject, string $body): string 41 | { 42 | return $this->emailService->send($to, $subject, $body); 43 | } 44 | } 45 | 46 | $adapater = new EmailServiceAdapter(new GoogleEmailService()); 47 | $adapter2 = new EmailServiceAdapter(new MicrosoftEmailService()); 48 | 49 | # echo $adapater->send('a@a.com', 'subject', 'body'); 50 | # echo $adapter2->send('a@a.com', 'subject', 'body'); 51 | -------------------------------------------------------------------------------- /projects-php/php-zend-certification/Structural/Decorator.php: -------------------------------------------------------------------------------- 1 | ninja->superpower()} + {$this->power}"; 58 | } 59 | } 60 | 61 | foreach ([ 62 | new NinjaKonoha, 63 | new NinjaKonoha, 64 | new NinjaSand, 65 | new NinjaSand, 66 | new NinjaStorm, 67 | new NinjaStone 68 | ] as $key => $value) { 69 | # echo PHP_EOL; 70 | # echo (new NinjaAddPowerDecorator($value, 'fire jutsu!'))->superpower() . ' new behavior :o'; 71 | } 72 | 73 | class NinjaSandExtraPower extends NinjaSand 74 | { 75 | 76 | public function __construct( 77 | private string $power = '' 78 | ) { 79 | } 80 | 81 | public function extra(): string 82 | { 83 | return parent::superpower() . " + {$this->power}"; 84 | } 85 | } 86 | 87 | class NinjaKonohaExtraPower extends NinjaKonoha 88 | { 89 | 90 | public function __construct( 91 | private string $power = '' 92 | ) { 93 | } 94 | 95 | public function extra(): string 96 | { 97 | return parent::superpower() . " + {$this->power}"; 98 | } 99 | } 100 | 101 | class NinjaStormExtraPower extends NinjaStorm 102 | { 103 | 104 | public function __construct( 105 | private string $power = '' 106 | ) { 107 | } 108 | 109 | public function extra(): string 110 | { 111 | return parent::superpower() . " + {$this->power}"; 112 | } 113 | } 114 | 115 | class NinjaStoneExtraPower extends NinjaStone 116 | { 117 | 118 | public function __construct( 119 | private string $power = '' 120 | ) { 121 | } 122 | 123 | public function extra(): string 124 | { 125 | return parent::superpower() . " + {$this->power}"; 126 | } 127 | } 128 | 129 | foreach ([ 130 | new NinjaKonohaExtraPower('fire jutsu!'), 131 | new NinjaKonohaExtraPower('fire jutsu!'), 132 | new NinjaSandExtraPower('sand jutsu!'), 133 | new NinjaSandExtraPower('sand jutsu!'), 134 | new NinjaStormExtraPower('storm jutsu!'), 135 | new NinjaStoneExtraPower('stone jutsu!') 136 | ] as $key => $value) { 137 | # echo PHP_EOL; 138 | # echo $value->extra() . ' new behavior :o'; 139 | } 140 | -------------------------------------------------------------------------------- /projects-php/php-zend-certification/Structural/Proxy.php: -------------------------------------------------------------------------------- 1 | $value) { 26 | echo PHP_EOL; 27 | 28 | /** @var NinjaInterface $ninja */ 29 | $ninja = (new NinjaPowerProxy($value, rand(1, 6))); 30 | echo $ninja()->superpower(); 31 | } 32 | 33 | class NinjaPowerProxy 34 | { 35 | 36 | public function __construct( 37 | private NinjaInterface $ninja, 38 | private string $password 39 | ) { 40 | } 41 | 42 | public function __invoke() 43 | { 44 | if (empty($this->password)) { 45 | throw new ErrorException('Password needs to be filled!', 403); 46 | } 47 | 48 | if ($this->password % 2 === 0) { 49 | return new NinjaAddPowerDecorator($this->ninja, 'special jutsu!'); 50 | } 51 | 52 | return new NinjaAddPowerDecorator($this->ninja, 'normal jutsu!'); 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /projects-php/php-zend-certification/certificate.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RazielRodrigues/php-projects/551e08b0b6aafea510a004dab9268b88c1b627f7/projects-php/php-zend-certification/certificate.png -------------------------------------------------------------------------------- /projects-php/php-zend-certification/readme.md: -------------------------------------------------------------------------------- 1 | # PHP Objects: Object Oriented Programming Software Patterns 2 | 3 | This repository is about my study from the course provided by ZEND, the company behind the PHP runtime 4 | in this course I have learned about the most used patterns of PHP which includes: 5 | 6 | 7 | 8 | I also have written articles about it on my dev.to profile 9 | 10 | The course is for free and you can also enroll clicking here 12 | 13 | Plus you get a nice certificate like this one :) 14 | 15 | 16 | 17 | git push git@github.com:RazielRodrigues/php-design-patterns-zend.git +new-project:master +site3a:rails3 18 | 19 | git remote add repoRemote https://bitbucket/repo/repo1.git -------------------------------------------------------------------------------- /projects-php/php-zend-certification/summary.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RazielRodrigues/php-projects/551e08b0b6aafea510a004dab9268b88c1b627f7/projects-php/php-zend-certification/summary.png --------------------------------------------------------------------------------