Você está na página 1de 15

Implementando MVC

Vamos apresentar a estrutura inicial para o backend de um e-


commerce de livros. Esta estrutura vai ser parte do nosso
projeto final.
index.php

app
Controller.php
Model.php
View.php
lib
Banco.php

view
home.php
livro.php
usuario.php

2
index.php
Caso existam classes, elas poderão ficar separadas:
<?php
function appLoad($classe) {
$arquivo = "app/$classe.php";
if(file_exists($arquivo)) {
require_once($arquivo);
}
}
function libLoad($classe) {
$arquivo = "lib/$classe.php";
if(file_exists($arquivo)) {
require_once($arquivo);
}
}
spl_autoload_register("appLoad");
spl_autoload_register("libLoad");

new Controller();

3
Controller.php
<?php
class Controller
{
public $view;
public $model;
public function __construct()
{
$this->view = new View();
$this->model = new Model();
$action = isset($_GET['action']) ? $_GET['action'] : null;
switch($_GET['action']) {
case 'livro':
$this->verLivro($_GET['id']);
break;
case 'usuario':
$this->verUsuario($_GET['id']);
break;
//continua

4
Controller.php
default:
$this->home();
break;
}
}
public function home()
{
$dados = $this->model->getContent();
$this->view->admin('home', $dados);
}
public function verLivro($id)
{
$dados = $this->model->getLivro($id);
$this->view->admin('livro', $dados);
}
public function verUsuario($id)
{
$dados = $this->model->getUsuario($id);
$this->view->admin('usuario', $dados);
}
}

5
Model.php
<?php
class Model
{
private $banco;
public function __construct()
{
$this->banco = Banco::instanciar();
}
public function getContent()
{
$conteudo['livros'] = $this->banco->listar('livros');
$conteudo['usuarios'] = $this->banco->listar('usuarios');
return $conteudo;
}
// continua

6
Model.php
public function getLivro($id)
{
return $this->banco->pesquisar('livro', “id=$id”);
}
public function getUsuario($id)
{
return $this->banco->pesquisar('usuario', “id=$id”);
}
}

7
Banco.php
<?php
class Banco
{
private static $instance;
private $host = "localhost";
private $db = "livraria";
private $user = "root";
private $pass = "123456";
// Core do singleton
public static function instanciar()
{
if(!self::$instance) {
self::$instance = new Banco();
self::$instance->conectar();
}
return self::$instance;
}
// continua

8
Banco.php
private function conectar()
{
$conexao = mysql_connect($this->host, $this->user, $this->pass);
if(!$conexao) {
die('Erro ao conectar ao banco de dados: ' . mysql_error());
}
if(!mysql_select_db($this->db)) {
die("Não foi possivel conectar ao database {$this->db}" .
mysql_error());
}
}
public function listar($tabela)
{
$rs = mysql_query("SELECT * FROM $tabela");
$results = array();
while($row = mysql_fetch_assoc($rs)) {
$results[] = $row;
}
return $results;
}
// continua

9
Banco.php
public function pesquisar($tabela, $condicao)
{
$rs = mysql_query("SELECT * FROM $tabela WHERE $condicao");
return mysql_fetch_assoc($rs);
}
}

10
View.php
<?php
class View
{
public function admin($caminho, $dados)
{
require("view/$caminho.php");
}
}

11
home.php
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Loja 501 - Admin</title>
</head>
<body>
<h1>Livros</h1>
<table border='1'>
<tr>
<th>ID</th>
<th>Titulo</th>
<th>ISBN</th>
<th>Preço</th>
</tr>
<?php foreach($dados['livros'] as $livro): ?>
<tr>
<td><?php echo $livro['id']; ?></td>
<td>
<a href="?action=livro&id=<?php echo $livro['id']; ?>">
<?php echo $livro['titulo']; ?></td>
</a>
</td>
<td><?php echo $livro['isbn']; ?></td>
<td><?php echo $livro['preco']; ?></td>
</tr>
<?php endforeach; ?>
</table>

12
home.php
<h1>Usuários</h1>
<table border='1'>
<tr>
<th>ID</th>
<th>Nome</th>
<th>Senha</th>
<th>Admin?</th>
</tr>
<?php foreach($dados['usuarios'] as $usuario): ?>
<tr>
<td><?php echo $usuario['id']; ?></td>
<td>
<a href="?action=usuario&id=<?php echo $usuario['id']; ?>">
<?php echo $usuario['nome']; ?></td>
</a>
</td>
<td><?php echo $usuario['senha']; ?></td>
<td><?php echo $usuario['is_admin'] ? 'X' : ''; ?></td>
</tr>
<?php endforeach; ?>
</table>
</body>
</html>

13
livro.php
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Loja 501 - Admin</title>
</head>
<body>
<h1><?php echo $dados['titulo']; ?></h1>
<p>
ID: <?php echo $dados['id']; ?><br />
ISBN: <?php echo $dados['isbn']; ?><br />
Título: <?php echo $dados['titulo']; ?><br />
Preço: <?php echo $dados['preco']; ?><br />
</p>
</body>
</html>

14
usuario.php
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Loja 501 - Admin</title>
</head>
<body>
<h1><?php echo $dados['nome']; ?></h1>
<p>
ID: <?php echo $dados['id']; ?><br />
Nome: <?php echo $dados['nome']; ?><br />
Senha: <?php echo $dados['senha']; ?><br />
Admin? <?php echo $dados['is_admin'] ? 'S' : 'N'; ?><br />
</p>
</body>
</html>

15

Você também pode gostar