5 CRUD MVC
Concesionario MVC
En el siguiente ejemplo veremos un Concesionario con el patrón Modelo-Vista-Controlador (MVC) y que realizará un CRUD para controlar y actualizar los registros para coches.
Depura el código
Se han omitido algunas palabras importantes en el código que debes depurar para su correcto funcionamiento. Se han sustituido por la palabra clave FALTACODIGO en 5 ocasiones
Podrás localizarlas fácilmente con la heramienta BUSCAR de tu IDE
Estructura de archivos
1. Archivo db.php
Define la conexión a la base de datos SQL.
<?php
$host = 'localhost';
$db = 'dwes';
$user = 'root'; // Cambia esto según tu configuración
$pass = ''; // Cambia esto según tu configuración
/* code that may potentially throw an exception, and if an exception is thrown within the `try` block, it can be caught and handled in the `catch` block. In the provided code snippet, the database connection
code is wrapped in a `try` block to catch any potential `PDOException` exceptions that may occur during the connection process.
If an exception is thrown, the code inside the `catch` block will
be executed to handle the error. */
try {
$pdo = new FALTACODIGO("mysql:host=$host;dbname=$db", $user, $pass);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo "Error de conexión: " . $e->getMessage();
}
?>
2. Modelo Coche.php
<?php
class Coche {
private $pdo;
public function __construct($pdo) {
$this->pdo = $pdo;
}
public function getAll() {
$stmt = $this->pdo->query("SELECT * FROM coches");
return $stmt->FALTACODIGO(PDO::FETCH_ASSOC);
//Viene en el Punto 3 PDO
}
public function crear($marca, $modelo, $anio) {
$stmt = $this->pdo->FALTACODIGO("INSERT INTO coches (marca, modelo, anio) VALUES (:marca, :modelo, :anio)");
$stmt->execute([':marca' => $marca, ':modelo' => $modelo, ':anio' => $anio]);
}
public function editar($id, $marca, $modelo, $anio) {
$stmt = $this->pdo->prepare("UPDATE coches SET marca = :marca, modelo = :modelo, anio = :anio WHERE id = :id");
$stmt->execute([':marca' => $marca, ':modelo' => $modelo, ':anio' => $anio, ':id' => $id]);
}
public function eliminar($id) {
$stmt = $this->pdo->prepare("DELETE FROM coches WHERE id = :id");
$stmt->execute([':id' => $id]);
}
public function getById($id) {
$stmt = $this->pdo->prepare("SELECT * FROM coches WHERE id = :id");
$stmt->execute([':id' => $id]);
return $stmt->fetch(PDO::FETCH_ASSOC);
}
}
3. Controlador CocheController.php
<?php
include 'db.php';
include 'models/Coche.php';
class CocheController {
private $cocheModel;
public function __construct($pdo) {
$this->cocheModel = new Coche($pdo);
}
public function index() {
$coches = $this->cocheModel->getAll();
include 'views/coches/index.php';
}
public function crear() {
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$this->cocheModel->crear($_POST['marca'], $_POST['modelo'], $_POST['anio']);
header("Location: index.php");
}
}
public function editar() {
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$this->cocheModel->editar($_POST['id'], $_POST['marca'], $_POST['modelo'], $_POST['anio']);
FALTACODIGO("Location: index.php");
}
}
public function eliminar() {
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$this->cocheModel->eliminar($_POST['id']);
header("Location: index.php");
}
}
}
?>
4. Vistas
index.php
(vista principal)
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<title>Gestión de Coches</title>
</head>
<body>
<h1>Gestión de Coches</h1>
<form method="POST" action="index.php?action=crear">
<input type="hidden" name="id" value="<?= isset($coche) ? $coche['id'] : '' ?>">
<label>Marca: <input type="text" name="marca" required></label><br>
<label>Modelo: <input type="text" name="modelo" required></label><br>
<label>Año: <input type="number" name="anio" required></label><br>
<button type="submit">Añadir Coche</button>
</form>
<h2>Lista
<h2>Lista de Coches</h2>
<table border="1">
<tr>
<th>ID</th>
<th>Marca</th>
<th>Modelo</th>
<th>Año</th>
<th>Acciones</th>
</tr>
<?php foreach ($coches as $coche): ?>
<tr>
<td><?= $coche['id'] ?></td>
<td><?= $coche['marca'] ?></td>
<td><?= $coche['modelo'] ?></td>
<td><?= $coche['anio'] ?></td>
<td>
<form method="POST" action="index.php?action=editar" style="display:inline;">
<input type="hidden" name="id" value="<?= $coche['id'] ?>">
<input type="text" name="marca" value="<?= $coche['marca'] ?>" required>
<input type="text" name="modelo" value="<?= $coche['modelo'] ?>" required>
<input type="number" name="anio" value="<?= $coche['anio'] ?>" required>
<button type="submit">Actualizar</button>
</form>
<form method="POST" action=FALTACODIGO style="display:inline;">
<input type="hidden" name="id" value="<?= $coche['id'] ?>">
<button type="submit">Eliminar</button>
</form>
</td>
</tr>
<?php endforeach; ?>
</table>
</body>
</html>
5. Archivo principal index.php
<?php
include 'controllers/CocheController.php';
$controller = new CocheController($pdo);
$action = $_GET['action'] ?? 'index';
switch ($action) {
case 'crear':
$controller->crear();
break;
case 'editar':
$controller->editar();
break;
case 'eliminar':
$controller->eliminar();
break;
default:
$controller->index();
break;
}
?>
6. Archivo database.sql
Usa este archivo para crear la base de datos y las tablas:
CREATE DATABASE coches_db;
USE coches_db;
CREATE TABLE coches (
id INT AUTO_INCREMENT PRIMARY KEY,
marca VARCHAR(50) NOT NULL,
modelo VARCHAR(50) NOT NULL,
anio INT NOT NULL
);
INSERT INTO coches (marca, modelo, anio) VALUES
('Toyota', 'Corolla', 2020),
('Honda', 'Civic', 2018),
('Ford', 'Focus', 2019);
PREPARACIÓN
- Crea la base de datos ejecutando el archivo
database.sql
en tu gestor SQL (phpMyAdmin o MySQL Workbench..). - Ajusta los valores en
config.php
para conectarte a tu servidor SQL.
CRUD
Debe resultar en un CRUD funcional que pueda actualizar coches