https://www.udemy.com/course/php-orientado-a-objetos-do-0-a-pratica/
Aprenda PHP Orientado a Objetos na prática! E ainda construa 5 projetos práticos.
- Introdução & Ambiente
- Configuração de Ambiente
- Conceitos Básicos de OO
- Métodos Mágicos
- Autoload & Namespaces
- Mais OO no PHP
- Exceptions
- Projeto 1 - Site Institucional
- Projeto 2 - Catálogo de Produtos
- Projeto 3 - Mini-Gerenciador de Gastos Pessoais
- Projeto 4 - Blog
- Break Up - Relacionamento entre Objetos
- Projeto Final - Primeira Etapa (Admin)
- Projeto Final - Segunda Etapa (Front Loja)
- Etapa Final - PagSeguro Checkout Transparente
Repositório do Instrutor:
- XAMPP + Condifg PHP in PATH
<?php
class car
{
public $color;
public $years;
public $model;
public function run()
{
return $this->model . " Car is Running";
}
public function stop()
{
return $this->model . " Car is Stop";
}
}
$car = new Car();
$car->model = "Car";
$car->color = "red";
$car->years = 2000;
$car2 = new Car();
$car2->model = "Car 2";
$car2->color = "blue";
$car2->years = 2020;
print $car->run();
print "\n";
print $car->stop();
print "\n";
print $car2->run();
print "\n";
print $car2->stop();
class car
{
public $color;
public $years;
public $model;
/**
* car constructor.
* @param $color
* @param $years
* @param $model
*/
public function __construct($color, $years, $model)
{
$this->color = $color;
$this->years = $years;
$this->model = $model;
}
public function run()
{
return $this->model . " Car is Running";
}
public function stop()
{
return $this->model . " Car is Stop";
}
public function __destruct()
{
print "\n REMOVENDO Objeto" . __CLASS__ ;
}
}
$car = new Car("Red", "2000", "HONDA");
//$car->model = "Car";
//$car->color = "red";
//$car->years = 2000;
$car2 = new Car("BLUE0", "2020", "RENAULT");
//$car2->model = "Car 2";
//$car2->color = "blue";
//$car2->years = 2020;
print $car->run();
print "\n";
print $car->stop();
print "\n";
print $car2->run();
print "\n";
print $car2->stop();
/*
HONDA Car is Running
HONDA Car is Stop
RENAULT Car is Running
RENAULT Car is Stop
REMOVENDO Objetocar
REMOVENDO Objetocar
*/
<?php
class Animal
{
public $name;
public function sleep()
{
return $this->name . " are sleeping... \n";
}
}
class Dog extends Animal
{
public function sleep()
{
print parent::sleep();
return "Dog SLEEEEEEEEPING \n";
}
}
class Bird extends Animal
{
}
$dog1 = new Dog();
$dog1->name = "TED";
print $dog1->sleep();
$bird = new Bird();
$bird->name = "Balack Bird";
print $bird->sleep();
<?php
class Person
{
public $name;
//protected $age = 30;
private $age = 30;
public function showName ()
{
return $this->name;
}
public function age()
{
return $this->age();
}
}
class Woman extends Person
{
public function showWomanAge()
{
//return $this->age;
return $this->age();
}
}
$person = new Woman();
$person->name = "Luci";
//$person->age = 20;
print $person->showName() . " " . $person->showWomanAge();
<?php
class BankAccount
{
public $balance = 0;
public function __construct()
{
$this->balance = 30;
}
public function deposit($money)
{
$this->balance += $money;
}
public function withDraw($money)
{
if ($money > $this->balance) {
return false;
}
$this->balance -= $money;
}
}
$bankAccaout1 = new BankAccount();
$bankAccaout1->deposit(10);
$bankAccaout1->deposit(20);
print $bankAccaout1->balance; // propriedade deve ser private
public function getBalance()
{
return $this->balance;
}
<?php
class Product
{
private $name;
private $price;
private $description;
public function getName()
{
return $this->name;
}
public function setName($name)
{
$this->name = $name;
}
public function getPrice()
{
return $this->price;
}
public function setPrice($price)
{
$this->price = $price;
}
public function getDescription()
{
return $this->description;
}
public function setDescription($description)
{
$this->description = $description;
}
}
$produto_1 = new Product();
$produto_1->setName("Vassoura");
$produto_1->setPrice(10);
$produto_1->setDescription("Vassoura TIpo 1");
print $produto_1->getName() . " Preço de R$ " . $produto_1->getPrice() ;
<?php
abstract class Animal
{
private $name;
public function run()
{
return "Animal is running";
}
abstract public function sound();
}
class Dog extends Animal
{
public function sound()
{
return "Au AU au";
}
}
$animal = new Dog();
print $animal->run();
print "\n";
print $animal->sound();
<?php
interface Animal
{
public function sound();
public function run();
}
class Dog implements Animal
{
public function sound()
{
return "Au au AU";
}
public function run()
{
return "DOG IS RUNNNN";
}
}
$dog1 = new Dog();
print $dog1->run();
print "\n";
print $dog1->sound();
print "\n";
print $dog1 instanceof Animal;
print "\n";
print $dog1 instanceof Dog;
/*
DOG IS RUNNNN
Au au AU
1
1
*/
<?php
abstract class Printer
{
public function toPrint()
{
return "Printing... original";
}
}
class HPPrinter extends Printer
{
public function toPrint()
{
return "Printing in HP....";
}
}
class Epson extends Printer
{
public function toPrint()
{
return "Pring in Epson";
}
/*
public function toPrint($papel) // PHP não permite
{
return $papel . " teste papel";
}
*/
}
$print = new Epson();
print $print->toPrint();
<?php
class Html
{
public static $mailTag = "<html>";
const END_TAG = "</html>";
public static function openTagHtml()
{
return self::$mailTag;
}
public static function EndTagHtml()
{
return self::END_TAG;
}
}
print Html::openTagHtml();
print Html::EndTagHtml();
print "\n";
print html::$mailTag;
print html::END_TAG;
<?php
final class User
{
private $name;
public function getName()
{
return $this->name;
}
final public function setName($name)
{
$this->name = $name;
}
}
<?php
class Produto
{
/* public function __set($name, $value)
{
var_dump($name, $value);
}*/
public $props = [];
public function __set($name, $value)
{
$this->props[$name] = $value;
}
public function __get($name)
{
return $this->props[$name];
}
}
$produto = new Produto();
$produto->name = "Prouto teste 1";
$produto->price = 12.99;
/*
string(4) "name"
string(14) "Prouto teste 1"
string(5) "price"
float(12.99)
*/
// var_dump($produto->props);
/*
array(2) {
["name"]=>
string(14) "Prouto teste 1"
["price"]=>
float(12.99)
}
*/
var_dump($produto->price);
<?php
class ProdutoCallCallStatic
{
public function __call($name, $arguments)
{
var_dump($name, $arguments);
/*
string(4) "save"
array(2) {
[0]=>
string(9) "Produto 1"
[1]=>
float(20.99)
}
*/
}
public static function __callStatic($name, $arguments)
{
var_dump($name, $arguments);
/*
array(2) {
[0]=>
string(8) "Conect 1"
[1]=>
int(200)
}
* */
}
}
$produto = new ProdutoCallCallStatic();
$produto->save("Produto 1", 20.99); // método não existe, com parametros
ProdutoCallCallStatic::getConnection("Conect 1", 200); // métodos estáticos
<?php
class ProtudosToString
{
public function __toString()
{
return "Retorno toString da classe " . __CLASS__; // sempre uma string ou exceptions v7.4
}
}
$produto = new ProtudosToString();
print $produto; // Retorno toString da classe ProtudosToString
<?php
//require __DIR__ . "/class/JsonExport.php";
//require __DIR__ . "/class/XmlExport.php";
function autoload($class)
{
require __DIR__ . "/class/".$class.".php";
}
spl_autoload_register('autoload');
if ($_GET['export'] == 'xml') {
print (new XmlExport())->doExport();
}
if ($_GET['export'] == 'json') {
print (new JsonExport())->doExport();
}
<?php
//require __DIR__ . "/class/JsonExport.php";
//require __DIR__ . "/class/XmlExport.php";
use Export\JsonExport;
use Export\XmlExport;
function autoload($class)
{
$baseFolder = __DIR__ . '/src/';
$class = str_replace('\\', '/', $class);
require $baseFolder . $class . '.php';
}
spl_autoload_register('autoload');
if ($_GET['export'] == 'xml') {
print (new XmlExport())->doExport();
}
if ($_GET['export'] == 'json') {
print (new JsonExport())->doExport();
}
<?php
namespace Export;
use Export\Contract\Export;
class JsonExport implements Export
{
public function doExport()
{
return "Json Export";
}
}
- 05-Autoload_Namespaces/nameSpace/src/Export/XmlExport.php
- 05-Autoload_Namespaces/nameSpace/src/Export/Contract/Export.php
<?php
namespace Export\Contract;
interface Export
{
}
<?php
//https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-4-autoloader-examples.md
spl_autoload_register(function ($class) {
// project-specific namespace prefix - namespace BASE
$prefix = 'Code\\';
// base directory for the namespace prefix
$base_dir = __DIR__ . '/src/';
// does the class use the namespace prefix?
$len = strlen($prefix);
if (strncmp($prefix, $class, $len) !== 0) {
// no, move to the next registered autoloader
return;
}
// get the relative class name
$relative_class = substr($class, $len);
// replace the namespace prefix with the base directory, replace namespace
// separators with directory separators in the relative class name, append
// with .php
$file = $base_dir . str_replace('\\', '/', $relative_class) . '.php';
// if the file exists, require it
if (file_exists($file)) {
require $file;
}
});
<?php
//require __DIR__ . "/class/JsonExport.php";
//require __DIR__ . "/class/XmlExport.php";
//use Export\JsonExport;
//use Export\XmlExport;
use Code\Export\{
JsonExport, XmlExport
};
require __DIR__ . '/autoload_psr4.php';
/*
function autoload($class)
{
$baseFolder = __DIR__ . '/src/';
$class = str_replace('\\', '/', $class);
require $baseFolder . $class . '.php';
}
spl_autoload_register('autoload');
*/
if ($_GET['export'] == 'xml') {
print (new XmlExport())->doExport();
}
if ($_GET['export'] == 'json') {
print (new JsonExport())->doExport();
}
<?php
namespace Code\Export;
use Code\Export\Contract\Export;
class XmlExport implements Export
{
public function doExport()
{
return "XML EXPORT";
}
}
- 05-Autoload_Namespaces/nameSpace/src/Export/JsonExport.php
- 05-Autoload_Namespaces/nameSpace/src/Export/Contract/Export.php
{
"autoload": {
"psr-4": {
"Code\\": "src/"
}
}
}
require __DIR__ . '/vendor/autoload.php';
composer dump
# ou
composer dump-autoload
<?php
declare(strict_types=1);
class Product
{
private $name;
private $price;
public function getName()
{
return $this->name;
}
public function setName(string $name)
{
$this->name = $name;
}
public function getPrice()
{
return $this->price;
}
public function setPrice(float $price)
{
$this->price = $price;
}
}
class Cart
{
private $itens = [];
public function addProduct(Product $product) // Declaração
{
$this->itens[] = $product;
}
public function getItens(): array // declaração tipo return
{
return $this->itens;
}
}
$produtuo1 = new Product();
$produtuo1->setName("Produto 1");
$produtuo1->setPrice(20.99);
$produtuo2 = new Product();
$produtuo2->setName("Produto 2");
$produtuo2->setPrice(100.99);
$cart = new Cart();
$cart->addProduct($produtuo1);
$cart->addProduct($produtuo2);
var_dump($cart->getItens());
/*
array(2) {
[0]=>
object(Product)#1 (2) {
["name":"Product":private]=>
string(9) "Produto 1"
["price":"Product":private]=>
float(20.99)
}
[1]=>
object(Product)#2 (2) {
["name":"Product":private]=>
string(9) "Produto 2"
["price":"Product":private]=>
float(100.99)
}
}
*/
print "PRoduto " . $produtuo1->getName() . "Preço R$ " . $produtuo1->getPrice();
// PRoduto Produto 1Preço R$ 20.99
<?php
trait uploadTrait
{
public function doUpload($file)
{
return true;
}
}
class Productss
{
use uploadTrait;
}
class Profile
{
use uploadTrait;
}
$prod1 = new Productss();
print $prod1->doUpload("arquivo...."); // 1
print "<br>";
$prod2 = new Profile();
print $prod2->doUpload("arquivo 2....");// 1
<?php
trait Mytrait
{
public function Hello()
{
return "Olá mundo Trait 1";
}
}
trait Mytrait2
{
public function showName($name)
{
return " Olá, " . $name;
}
public function Hello()
{
return "Olá mundo de Trait 2";
}
}
class Client
{
use Mytrait, Mytrait2 {
Mytrait2::Hello insteadof Mytrait; // usar o hello de mytrait
Mytrait::Hello as AliasHellow; // ALIAS
Mytrait::Hello as private helloVisibilitPrivate; // modificando a visibilidade do método
}
public function teste()
{
return $this->helloVisibilitPrivate();
}
}
$c = new Client();
print $c->Hello();
print "<br>";
print $c->AliasHellow();
print "<br>";
print $c->showName("José");
<?php
$classAnonymous = new class{
public function log($message)
{
return $message;
}
};
class BackAccount
{
public function withDraw($value, $classAnonymous)
{
return $classAnonymous->log("Loggin... WithDraw....");
}
}
$bank = new BackAccount();
print $bank->withDraw(20, $classAnonymous);
// Loggin... WithDraw....
<?php
use CodeException\Sum;
require __DIR__ . "/vendor/autoload.php";
try {
$sum = new Sum();
print $sum->doSum(10);
}catch (\Error $e){
print_r($e->getTrace());
}
<?php
use CodeException\Sum;
require __DIR__ . "/vendor/autoload.php";
try {
$sum = new Sum();
print $sum->doSum(10, 9);
}catch (\Error $e){
print_r($e->getTrace());
}catch (\Exception $e){
print $e->getMessage();
}
<?php
namespace CodeException;
class Sum{
public function doSum($num1, $num2)
{
if ($num2 >= 10) {
throw new \Exception("Parametro 2 deve ser menor ou igual a 10");
}
return $num1 + $num2;
}
}
<?php
namespace CodeException\MyExceptions;
use Throwable;
class MyCustomException extends \Exception
{
/**
* MyCustomException constructor.
*/
public function __construct($message = "Minha Mensagem customizada", $code = 0, Throwable $previous = null)
{
parent::__construct($message, $code, $previous);
}
}
<?php
use CodeException\Sum;
require __DIR__ . "/vendor/autoload.php";
try {
$sum = new Sum();
print $sum->doSum(10, 20);
}/* catch (\Error $e) {
print_r($e->getTrace());
}*/ catch (\CodeException\MyExceptions\MyCustomException $e) {
print $e->getMessage();
}
<?php
use CodeException\Sum;
require __DIR__ . "/vendor/autoload.php";
try {
$sum = new Sum();
print $sum->doSum(10, 9);
} catch (\Error $e) {
print_r($e->getTrace());
} catch (\CodeException\MyExceptions\MyCustomException $e) {
print $e->getMessage();
} finally {
print " Finaly"; // Save de um log
}
<?php
require __DIR__ . '/../08-Projeto-1-Site_Institucional/vendor/autoload.php';
$url = substr($_SERVER['REQUEST_URI'], 1);
$url = explode('/', $url);
$controller = isset($url[0]) && $url[0] ? $url[0] : 'page';
$action = isset($url[1]) && $url[1] ? $url[1] : 'index';
$param = isset($url[2]) && $url[2] ? $url[2] : null;
if (!class_exists($controller = "\Code\Controller\\" . ucfirst($controller) . 'Controller')) {
die("404 - Página não encontrada");
}
if (!method_exists($controller, $action)) {
$action = 'index';;
$param = $url[1];
}
$response = call_user_func_array([new $controller, $action], [$param]);
print $response;
<?php
namespace Code\DB;
use \PDO;
abstract class Entity
{
/**
* @var PDO
*/
private $con;
protected $table;
/**
* Entity constructor.
*/
public function __construct(PDO $con)
{
$this->con = $con;
}
public function findAll($fields = '*')
{
$sql = 'SELECT ' . $fields . ' FROM ' . $this->table;
$get = $this->con->query($sql);
return $get->fetchAll(PDO::FETCH_ASSOC);
}
public function find(int $id)
{
$sql = 'SELECT * FROM products WHERE id = :id';
$get = $this->con->prepare($sql);
$get->bindValue(':id', $id, PDO::PARAM_INT);
$get->execute();
return $get->fetch(PDO::FETCH_ASSOC);
}
public function where(array $conditions, $operador = ' AND ', $fields = '*')
{
$sql = 'SELECT ' . $fields . ' FROM ' . $this->table . ' WHERE ';
$binds = array_keys($conditions);
$where = null;
foreach ($binds as $v) {
if (is_null($where)) {
$where .= $v . ' = :' . $v;
} else {
$where .= $operador . $v . ' = :' . $v;
}
}
$sql .= $where;
$get = $this->con->prepare($sql);
foreach ($conditions as $k => $v) {
gettype($v == 'int' ? $get->bindValue(':' . $k, $v, \PDO::PARAM_INT)
: $get->bindValue(':' . $k, $v, \PDO::PARAM_STR));
}
$get->execute();
return $get->fetchAll(\PDO::FETCH_ASSOC);
}
}
public function insert($data)
{
$binds = array_keys($data);
$sql = 'INSERT INTO ' . $this->table . ' ('. implode(', ', $binds) .', created_at, updated_at)
VALUES(:'. implode(', :', $binds) .', NOW(), NOW()) ';
//print $sql;
$insert = $this->bind($sql, $data);
return $insert->execute();
}
private function bind($sql, $data)
{
$bind = $this->con->prepare($sql);
foreach ($data as $k => $v) {
gettype($v) == 'int' ? $bind->bindValue(':' . $k, $v, \PDO::PARAM_INT)
: $bind->bindValue(':' . $k, $v, \PDO::PARAM_STR);
}
//var_dump($get);
return $bind;
}
public function update($data)
{
if (!array_key_exists('id', $data)) {
throw new \Exception('é preciso informar um ID válido para o UPDATE');
}
$sql = 'UPDATE '. $this->table . ' SET ' ;
$set = null;
$binds = array_keys($data);
foreach ($binds as $v) {
if ($v !== 'id') {
$set .= is_null($set) ? $v . ' = :' . $v : ', ' . $v . ' = :' . $v;
}
}
$sql .= $set . ', updated_at = NOW() WHERE id = :id';
$update = $this->bind($sql, $data);
return $update->execute();
}
public function delete(int $id): bool
{
$sql = 'DELETE FROM ' . $this->table . ' WHERE id = :id';
$delete = $this->bind($sql, ['id'=> $id]);
return $delete->execute();
}