Wilfredo Meneses
Profesor universitario
¿Por qué variables?
<?php
$greetings = "Hola";
$name = "Wilfredo";
echo "{$greetings}, $name";<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
header{
background-color: gray;
padding: 2em;
text-align: center;
}
</style>
</head>
<body>
<header>
<h1>
<?php echo "Hola, ".htmlspecialchars($_GET['name']); ?>
</h1>
</header>
</body>
</html>Palabras claves: Inyección de código, sanitizing
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<header>
<h1>
<?= $greeting; ?>
</h1>
</header>
</body>
</html>index.view.php
Presentación
<?php
$greeting = 'Hola Mundo';
require 'index.view.php';index.php
Lógica - datos
Palabra clave: responsabilidad
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<ul>
<?php foreach($names as $name): ?>
<li><?= $name; ?></li>
<?php endforeach ?>
<?php
foreach($names as $name) {
echo "<li>$name</li>";
}
?>
</ul>
</body>
</html>index.view.php
Presentación
<?php
$names = [
'Wilfredo',
'Luisa',
'Joshua'
];
require 'index.view.php';index.php
Lógica - datos
Ejercicio: crear un arreglo de cinco animales, recorrerlos con un ciclo y mostrarlos en pantalla con una lista
<?php
$person = [
'age' => 35,
'hair' => 'Castaño',
'career' => 'Desarrollador Web'
];
$person ['name'] = 'Wilfredo';
unset ($person['age']);
// echo $person;
// Genera un error porque espera un string
die(var_dump($person));
require 'index.view.php';<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<ul>
<?php foreach ($person as $key=> $feature):?>
<li><strong><?= $key; ?> </strong><?= $feature; ?></li>
<?php endforeach; ?>
</ul>
</body>
</html>index.view.php
index.php
Ejercicio: crear un arreglo asociativo de tareas, con detalle como title, due, assigned_to, completed
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<h1>Tareas para hoy</h1>
<ul>
<?php foreach ($task as $heading=> $val):?>
<li><strong><?= ucwords($heading); ?>: </strong><?= $val; ?></li>
<?php endforeach; ?>
</ul>
</body>
</html><?php
$task = [
'title' => 'Finalizar la tarea',
'due' => 'hoy',
'assigned_to' => 'Wilfredo',
'completed' => false
];
require 'index.view.php';
index.php
index.view.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<h1>Tareas para hoy</h1>
<ul>
<li><strong>Título: </strong><?= $task['title']; ?></li>
</ul>
<ul>
<li><strong>Vence: </strong><?= $task['due']; ?></li>
</ul>
<ul>
<li><strong>Asignado a: </strong><?= $task['assigned_to']; ?></li>
</ul>
<ul>
<li><strong>Estado: </strong><?= $task['completed'] ? 'Completado' : 'Pendiente'; ?></li>
</ul>
</body>
</html><?php
$task = [
'title' => 'Finalizar la tarea',
'due' => 'hoy',
'assigned_to' => 'Wilfredo',
'completed' => false
];
require 'index.view.php';
index.php
index.view.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<h1>Tareas para hoy</h1>
<ul>
<li><strong>Título: </strong><?= $task['title']; ?></li>
</ul>
<ul>
<li><strong>Vence: </strong><?= $task['due']; ?></li>
</ul>
<ul>
<li><strong>Asignado a: </strong><?= $task['assigned_to']; ?></li>
</ul>
<ul>
<li><strong>Estado: </strong>
<?php if($task['completed']) : ?>
<span> ✅ </span>
<?php endif ?>
</li>
</ul>
</body>
</html><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<h1>Tareas para hoy</h1>
<ul>
<li><strong>Título: </strong><?= $task['title']; ?></li>
</ul>
<ul>
<li><strong>Vence: </strong><?= $task['due']; ?></li>
</ul>
<ul>
<li><strong>Asignado a: </strong><?= $task['assigned_to']; ?></li>
</ul>
<ul>
<li><strong>Estado: </strong>
<?php
if($task['completed']) {
echo "✅";
} else {
echo "Pendiente";
}
?>
</li>
</ul>
</body>
</html>
(1)
(2)
<?php
function dd ($data) {
echo '<pre>';
die(var_dump($data));
echo '</pre>';
}<?php
require 'functions.php';
$task = [
'title' => 'Finalizar la tarea',
'due' => 'hoy',
'assigned_to' => 'Wilfredo',
'completed' => true
];
$animals = ['perro', 'gato', 'ardilla'];
dd($animals);
require 'index.view.php';
index.php
functions.php
Ejercicio: realice una función que dada una edad determine si puede o no ingresar a un club de negocios, la respuesta debe ser Boolean (ingresan solo si la edad es mayor que 18 años )
-- Mostrar las bases de datos
show databases;
drop database if exists MyTodo;
create database MyTodo;
-- Ver la base de datos creadas
show databases;
-- Usar la base de datos
use MyTodo;
-- Ver las tablas
show tables;
-- Crear una tabla
create table todos (description text, completed boolean);
-- Ver lqa estructura de la tabla creada
describe todos;
-- Eliminar tabla
drop table todos;
create table todos (description text NOT NULL, completed boolean NOT NULL);
describe todos;
drop table todos;
-- Agregamos una clave
create table todos (id integer PRIMARY KEY AUTO_INCREMENT, description text NOT NULL, completed boolean NOT NULL);
describe todos;
-- Insertar registros
insert into todos (description, completed) values ('Ir a la tienda', false);
-- Ver registros
select * from todos;
insert into todos (description, completed) values ('Finalizar el ensayo', false);
select * from todos where id = 2;Ejercicio: cree una tabla que contemple por lo menos tres campos y 4 registros y practique las operaciones realizadas durante esta sección.
Clave: Clases, objetos, constructor, Diferencias entre métodos y funciones, atributos (estados), encapsulamiento
<?php
require 'functions.php';
class Task {
protected $description;
protected $completed = false;
public function __construct($description)
{
// Este método se desencadena cuando se instancia un objeto de la clase
// También llamados constructores
$this->description = $description;
}
public function isComplete() {
return $this->completed;
}
public function complete() {
$this->completed = true;
}
}
$task = new Task('Ir a la tienda'); //Nuevo objeto de tarea
$task->complete(); // Completar la tarea
dd($task->isComplete()); // Verificar si la tarea ha sido completada
require 'index.view.php';
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<h1>Tareas para hoy</h1>
<ul>
<?php foreach($tasks as $task): ?>
<li>
<?php if ($task->completed): ?>
<strike> <?= $task->description; ?> </strike>
<?php else: ?>
<?= $task->description; ?>
<?php endif ?>
</li>
<?php endforeach ?>
</ul>
</body>
</html><?php
class Task {
public $description;
public $completed = false;
public function __construct($description)
{
// Este método se desencadena cuando se instancia un objeto de la clase
// También llamados constructores
$this->description = $description;
}
public function isComplete() {
return $this->completed;
}
public function complete() {
$this->completed = true;
}
}
$tasks = [
new Task('Ir a la tienda'), // 1
new Task('Finalizar el ensayo'), // 2
new Task('Limpiar mi cuarto'), // 3
];
$tasks[0]->complete();
require 'index.view.php';
index.php
index.view.php
<?php
try{
$pdo = new PDO('mysql:host=127.0.0.1;dbname=mytodo', 'root', '');
} catch(PDOException $e){
//die($e->getMessage());
die('No se pudo establecer la conexión con la base de datos');
}
$statement = $pdo->prepare('select * from todos');
$statement->execute();
// var_dump($statement->fetchAll(PDO::FETCH_OBJ));
$tasks = ($statement->fetchAll(PDO::FETCH_OBJ));
// var_dump($todos[0]->description);
require 'index.view.php';
index.php
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Learning-PHP</title>
</head>
<body>
<ul>
<?php foreach($tasks as $task): ?>
<li>
<?php if($task->completed): ?>
<strike><?= $task->description; ?></strike>
<?php else: ?>
<?= $task->description; ?>
<?php endif ?>
</li>
<?php endforeach; ?>
</ul>
</body>
</html>index.view.php
<?php
require 'Task.php';
try{
$pdo = new PDO('mysql:host=127.0.0.1;dbname=mytodo', 'root', '');
} catch(PDOException $e){
//die($e.getMessage());
die('No se pudo establecer la conexión con la base de datos');
}
$statement = $pdo->prepare('select * from todos');
$statement->execute();
// var_dump($statement->fetchAll(PDO::FETCH_OBJ));
$tasks = ($statement->fetchAll(PDO::FETCH_CLASS, 'Task'));
// var_dump($todos[0]->description);
require 'index.view.php';index.php
<?php
class Task
{
public $description;
public $completed;
}Task.php
<?php
require 'functions.php';
require 'Task.php';
$pdo = connectToDB();
$tasks = fetchAllTasks($pdo);
require 'index.view.php';index.php
<?php
function connectToDB() {
try{
return $pdo = new PDO('mysql:host=127.0.0.1;dbname=mytodo', 'root', '');
} catch(PDOException $e){
//die($e.getMessage());
die('No se pudo establecer la conexión con la base de datos');
}
};
function fetchAllTasks($pdo) {
$statement = $pdo->prepare('select * from todos');
$statement->execute();
return $statement->fetchAll(PDO::FETCH_CLASS, 'Task');
}
function dd ($data) {
echo '<pre>';
die(var_dump($data));
echo '</pree>';
}functions.php
La refactorización, o en inglés refactoring, es:
Sus objetivos pueden ser:
<?php
class Connection
{
public static function make()
{
try{
return $pdo = new PDO('mysql:host=127.0.0.1;dbname=mytodo', 'root', '');
} catch(PDOException $e){
//die($e.getMessage());
die('No se pudo establecer la conexión con la base de datos');
}
}
}database/QueryBuilder.php
Responsabilidades: database/connection.php
<?php
class QueryBuilder
{
protected $pdo;
function __construct(PDO $pdo)
{
$this->pdo = $pdo;
}
function selectAll($table) {
$statement = $this->pdo->prepare("select * from {$table}");
$statement->execute();
return $statement->fetchAll(PDO::FETCH_CLASS);
}
}<?php
require 'database/Connection.php';
require 'database/QueryBuilder.php';
$pdo = Connection::make();
$query = new QueryBuilder($pdo);
$tasks = $query->selectAll('todos');
require 'index.view.php';
index.php
<?php
require 'database/Connection.php';
require 'database/QueryBuilder.php';
return new QueryBuilder(
Connection::make()
);bootstrap.php
<?php
$database = require 'bootstrap.php';
$tasks = $database->selectAll('todos');
require 'index.view.php';index.php
<?php
return [
'database' => [
'name' => 'mytodo',
'user' => 'root',
'password' => '',
'connection' => 'mysql:host=127.0.0.1',
'options' => [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
]
]
];config.php
<?php
$config = require 'config.php';
require 'database/Connection.php';
require 'database/QueryBuilder.php';
return new QueryBuilder(
Connection::make($config['database'])
);bootstrap.php
<?php
class Connection
{
public static function make($config)
{
try{
// return $pdo = new PDO('mysql:host=127.0.0.1;dbname=mytodo', 'root', '');
return new PDO (
$config['connection'].';dbname='.$config['name'],
$config['user'],
$config['password'],
$config['options']
);
} catch(PDOException $e){
//die($e.getMessage());
die('No se pudo establecer la conexión con la base de datos');
}
}
}connection.php
By Wilfredo Meneses