Created
June 27, 2018 21:03
-
-
Save alxbbarbosa/38e43278441a0d82f50f74b68f5b9702 to your computer and use it in GitHub Desktop.
Apresentação do código de exemplo MVC para o Blog
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class Conexao | |
{ | |
private static $conexao; | |
private function __construct() | |
{} | |
public static function getInstance() | |
{ | |
if (is_null(self::$conexao)) { | |
self::$conexao = new \PDO('mysql:host=localhost;port=3306;dbname=projeto_mvc', 'root', 'P@ssw0rd'); | |
self::$conexao->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION); | |
self::$conexao->exec('set names utf8'); | |
} | |
return self::$conexao; | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Classe Contato - baseado no modelo Active Record (Simplificado) | |
* @author Alexandre Bezerra Barbosa | |
*/ | |
class Contato | |
{ | |
private $atributos; | |
public function __construct() | |
{ | |
} | |
public function __set(string $atributo, $valor) | |
{ | |
$this->atributos[$atributo] = $valor; | |
return $this; | |
} | |
public function __get(string $atributo) | |
{ | |
return $this->atributos[$atributo]; | |
} | |
public function __isset($atributo) | |
{ | |
return isset($this->atributos[$atributo]); | |
} | |
/** | |
* Salvar o contato | |
* @return boolean | |
*/ | |
public function save() | |
{ | |
$colunas = $this->preparar($this->atributos); | |
if (!isset($this->id)) { | |
$query = "INSERT INTO contatos (". | |
implode(', ', array_keys($colunas)). | |
") VALUES (". | |
implode(', ', array_values($colunas)).");"; | |
} else { | |
foreach ($colunas as $key => $value) { | |
if ($key !== 'id') { | |
$definir[] = "{$key}={$value}"; | |
} | |
} | |
$query = "UPDATE contatos SET ".implode(', ', $definir)." WHERE id='{$this->id}';"; | |
} | |
if ($conexao = Conexao::getInstance()) { | |
$stmt = $conexao->prepare($query); | |
if ($stmt->execute()) { | |
return $stmt->rowCount(); | |
} | |
} | |
return false; | |
} | |
/** | |
* Tornar valores aceitos para sintaxe SQL | |
* @param type $dados | |
* @return string | |
*/ | |
private function escapar($dados) | |
{ | |
if (is_string($dados) & !empty($dados)) { | |
return "'".addslashes($dados)."'"; | |
} elseif (is_bool($dados)) { | |
return $dados ? 'TRUE' : 'FALSE'; | |
} elseif ($dados !== '') { | |
return $dados; | |
} else { | |
return 'NULL'; | |
} | |
} | |
/** | |
* Verifica se dados são próprios para ser salvos | |
* @param array $dados | |
* @return array | |
*/ | |
private function preparar($dados) | |
{ | |
$resultado = array(); | |
foreach ($dados as $k => $v) { | |
if (is_scalar($v)) { | |
$resultado[$k] = $this->escapar($v); | |
} | |
} | |
return $resultado; | |
} | |
/** | |
* Retorna uma lista de contatos | |
* @return array/boolean | |
*/ | |
public static function all() | |
{ | |
$conexao = Conexao::getInstance(); | |
$stmt = $conexao->prepare("SELECT * FROM contatos;"); | |
$result = array(); | |
if ($stmt->execute()) { | |
while ($rs = $stmt->fetchObject(Contato::class)) { | |
$result[] = $rs; | |
} | |
} | |
if (count($result) > 0) { | |
return $result; | |
} | |
return false; | |
} | |
/** | |
* Retornar o número de registros | |
* @return int/boolean | |
*/ | |
public static function count() | |
{ | |
$conexao = Conexao::getInstance(); | |
$count = $conexao->exec("SELECT count(*) FROM contatos;"); | |
if ($count) { | |
return (int) $count; | |
} | |
return false; | |
} | |
/** | |
* Encontra um recurso pelo id | |
* @param type $id | |
* @return type | |
*/ | |
public static function find($id) | |
{ | |
$conexao = Conexao::getInstance(); | |
$stmt = $conexao->prepare("SELECT * FROM contatos WHERE id='{$id}';"); | |
if ($stmt->execute()) { | |
if ($stmt->rowCount() > 0) { | |
$resultado = $stmt->fetchObject('Contato'); | |
if ($resultado) { | |
return $resultado; | |
} | |
} | |
} | |
return false; | |
} | |
/** | |
* Destruir um recurso | |
* @param type $id | |
* @return boolean | |
*/ | |
public static function destroy($id) | |
{ | |
$conexao = Conexao::getInstance(); | |
if ($conexao->exec("DELETE FROM contatos WHERE id='{$id}';")) { | |
return true; | |
} | |
return false; | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class ContatosController extends Controller | |
{ | |
/** | |
* Lista os contatos | |
*/ | |
public function listar() | |
{ | |
$contatos = Contato::all(); | |
return $this->view('grade', ['contatos' => $contatos]); | |
} | |
/** | |
* Mostrar formulario para criar um novo contato | |
*/ | |
public function criar() | |
{ | |
return $this->view('form'); | |
} | |
/** | |
* Mostrar formulário para editar um contato | |
*/ | |
public function editar($dados) | |
{ | |
$id = (int) $dados['id']; | |
$contato = Contato::find($id); | |
return $this->view('form', ['contato' => $contato]); | |
} | |
/** | |
* Salvar o contato submetido pelo formulário | |
*/ | |
public function salvar() | |
{ | |
$contato = new Contato; | |
$contato->nome = $this->request->nome; | |
$contato->telefone = $this->request->telefone; | |
$contato->email = $this->request->email; | |
if ($contato->save()) { | |
return $this->listar(); | |
} | |
} | |
/** | |
* Atualizar o contato conforme dados submetidos | |
*/ | |
public function atualizar($dados) | |
{ | |
$id = (int) $dados['id']; | |
$contato = Contato::find($id); | |
$contato->nome = $this->request->nome; | |
$contato->telefone = $this->request->telefone; | |
$contato->email = $this->request->email; | |
$contato->save(); | |
return $this->listar(); | |
} | |
/** | |
* Apagar um contato conforme o id informado | |
*/ | |
public function excluir($dados) | |
{ | |
$id = (int) $dados['id']; | |
$contato = Contato::destroy($id); | |
return $this->listar(); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class Controller | |
{ | |
public $request; | |
public function __construct() | |
{ | |
$this->request = new Request; | |
} | |
public function view($arquivo, $array = null) | |
{ | |
if (!is_null($array)) { | |
foreach ($array as $var => $value) { | |
${$var} = $value; | |
} | |
} | |
ob_start(); | |
include "{$arquivo}.php"; | |
ob_flush(); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<div class="container"> | |
<form action="?controller=ContatosController&<?php echo isset($contato->id) ? "method=atualizar&id={$contato->id}" : "method=salvar"; ?>" method="post" > | |
<div class="card" style="top:40px"> | |
<div class="card-header"> | |
<span class="card-title">Contatos</span> | |
</div> | |
<div class="card-body"> | |
</div> | |
<div class="form-group form-row"> | |
<label class="col-sm-2 col-form-label text-right">Nome:</label> | |
<input type="text" class="form-control col-sm-8" name="nome" id="nome" value="<?php | |
echo isset($contato->nome) ? $contato->nome : null; | |
?>" /> | |
</div> | |
<div class="form-group form-row"> | |
<label class="col-sm-2 col-form-label text-right">Telefone:</label> | |
<input type="text" class="form-control col-sm-8" name="telefone" id="telefone" value="<?php | |
echo isset($contato->telefone) ? $contato->telefone : null; | |
?>" /> | |
</div> | |
<div class="form-group form-row"> | |
<label class="col-sm-2 col-form-label text-right">Email:</label> | |
<input type="text" class="form-control col-sm-8" name="email" id="email" value="<?php | |
echo isset($contato->email) ? $contato->email : null; | |
?>" /> | |
</div> | |
<div class="card-footer"> | |
<input type="hidden" name="id" id="id" value="<?php echo isset($contato->id) ? $contato->id : null; ?>" /> | |
<button class="btn btn-success" type="submit">Salvar</button> | |
<button class="btn btn-secondary">Limpar</button> | |
<a class="btn btn-danger" href="?controller=ContatosController&method=listar">Cancelar</a> | |
</div> | |
</div> | |
</form> | |
</div> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<h1>Contatos</h1> | |
<hr> | |
<div class="container"> | |
<table class="table table-bordered table-striped" style="top:40px;"> | |
<thead> | |
<tr> | |
<th>Nome</th> | |
<th>Telefone</th> | |
<th>Email</th> | |
<th><a href="?controller=ContatosController&method=criar" class="btn btn-success btn-sm">Novo</a></th> | |
</tr> | |
</thead> | |
<tbody> | |
<?php | |
if ($contatos) { | |
foreach ($contatos as $contato) { | |
?> | |
<tr> | |
<td><?php echo $contato->nome; ?></td> | |
<td><?php echo $contato->telefone; ?></td> | |
<td><?php echo $contato->email; ?></td> | |
<td> | |
<a href="?controller=ContatosController&method=editar&id=<?php echo $contato->id; ?>" class="btn btn-primary btn-sm">Editar</a> | |
<a href="?controller=ContatosController&method=excluir&id=<?php echo $contato->id; ?>" class="btn btn-danger btn-sm">Excluir</a> | |
</td> | |
</tr> | |
<?php | |
} | |
} else { | |
?> | |
<tr> | |
<td colspan="5">Nenhum registro encontrado</td> | |
</tr> | |
<?php | |
} | |
?> | |
</tbody> | |
</table> | |
</div> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
error_reporting(E_ALL); | |
ini_set('display_errors', true); | |
spl_autoload_register(function($class) { | |
if (file_exists("$class.php")) { | |
require_once "$class.php"; | |
return true; | |
} | |
}); | |
?> | |
<!DOCTYPE html> | |
<html lang='pt-br'> | |
<header> | |
<meta charset="utf-8"> | |
<title>Agenda de contatos</title> | |
<link href='https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css' rel='stylesheet' integrity='sha384-WskhaSGFgHYWDcbwN70/dfYBj47jz9qbsMId/iRN3ewGhXQFZCSftd1LZCfmhktB' crossorigin='anonymous' /> | |
<link href='https://use.fontawesome.com/releases/v5.1.0/css/all.css' rel='stylesheet' integrity='sha384-lKuwvrZot6UHsBSfcMvOkWwlCMgc0TaWr+30HWe3a4ltaBwTZhyTEggF5tJv8tbt' crossorigin='anonymous' /> | |
<script src='https://code.jquery.com/jquery-3.3.1.slim.min.js' integrity='sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo' crossorigin='anonymous'></script> | |
<script src='https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js' integrity='sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49' crossorigin='anonymous'></script> | |
<script src='https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js' integrity='sha384-smHYKdLADwkXOn1EmN1qk/HfnUcbVRZyYmZ4qpPea6sjB/pTJ0euyQp0Mk8ck+5T' crossorigin='anonymous'></script> | |
</header> | |
<body> | |
<?php | |
if ($_GET) { | |
$controller = isset($_GET['controller']) ? ((class_exists($_GET['controller'])) ? new $_GET['controller'] : NULL ) : null; | |
$method = isset($_GET['method']) ? $_GET['method'] : null; | |
if ($controller && $method) { | |
if (method_exists($controller, $method)) { | |
$parameters = $_GET; | |
unset($parameters['controller']); | |
unset($parameters['method']); | |
call_user_func(array($controller, $method), $parameters); | |
} else { | |
echo "Método não encontrado!"; | |
} | |
} else { | |
echo "Controller não encontrado!"; | |
} | |
} else { | |
echo '<h1>Contatos</h1><hr><div class="container">'; | |
echo 'Bem-vindo ao aplicativo MVC Contatos! <br /><br />'; | |
echo '<a href="?controller=ContatosController&method=listar" class="btn btn-success">Vamos Começar!</a></div>'; | |
} | |
?> | |
</body> | |
</html> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class Request | |
{ | |
protected $request; | |
public function __construct() | |
{ | |
$this->request = $_REQUEST; | |
} | |
public function __get($nome) | |
{ | |
if (isset($this->request[$nome])) { | |
return $this->request[$nome]; | |
} | |
return false; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment