1
<?php
declare(strict_types=1);
// 1. Trait para Gestión de Marcas de Tiempo
trait ConMarcasDeTiempo
{
private string $creadoEn;
private string $actualizadoEn;
public function inicializarFechas(): void
{
$ahora = date('Y-m-d H:i:s');
$this->creadoEn = $ahora;
$this->actualizadoEn = $ahora;
}
public function tocarActualizacion(): void
{
$this->actualizadoEn = date('Y-m-d H:i:s');
}
public function getInfoFechas(): string
{
return "Creado: {$this->creadoEn} | Modificado: {$this->actualizadoEn}";
}
}
// 2. Trait para Generación de Slugs Amigables
trait ConSlugAmigable
{
public function crearSlug(string $titulo): string
{
$slug = preg_replace('~[^\pL\d]+~u', '-', $titulo);
$slug = iconv('utf-8', 'us-ascii//TRANSLIT', $slug);
$slug = preg_replace('~[^-\w]+~', '', $slug);
$slug = trim($slug, '-');
$slug = preg_replace('~-+~', '-', $slug);
return strtolower($slug);
}
}
// 3. Clase A: Producto de la Tienda
class ProductoTienda
{
// Inyección de ambos traits
use ConMarcasDeTiempo, ConSlugAmigable;
public function __construct(
public readonly string $titulo,
public readonly float $precio
) {
$this->inicializarFechas();
}
public function getUrl(): string
{
return "https://mitienda.com/p/" . $this->crearSlug($this->titulo);
}
}
// 4. Clase B: Artículo de Blog (Completamente diferente a un producto)
class ArticuloBlog
{
use ConMarcasDeTiempo, ConSlugAmigable;
public function __construct(
public readonly string $encabezado,
public readonly string $autor
) {
$this->inicializarFechas();
}
public function getUrl(): string
{
return "https://mitienda.com/blog/" . $this->crearSlug($this->encabezado);
}
}
// ==========================================
// PRUEBA EN EL SANDBOX
// ==========================================
$producto = new ProductoTienda("Monitor Gamer Curvo 34'' OLED", 799.00);
$post = new ArticuloBlog("Los 10 Mejores Principios de POO en PHP 8.3", "Profesor Kilopolis");
echo "<h2>Reutilización Horizontal con Traits:</h2>";
echo "<div style='font-family:system-ui; background:#f1f5f9; padding:15px; border-radius:8px; margin-bottom:12px;'>";
echo "<h3>📦 Producto: {$producto->titulo}</h3>";
echo "<p><strong>URL Generada con Trait:</strong> <a href='#'>{$producto->getUrl()}</a></p>";
echo "<small style='color:#64748b;'>{$producto->getInfoFechas()}</small>";
echo "</div>";
echo "<div style='font-family:system-ui; background:#f1f5f9; padding:15px; border-radius:8px;'>";
echo "<h3>📰 Post de Blog: {$post->encabezado}</h3>";
echo "<p><strong>URL Generada con Trait:</strong> <a href='#'>{$post->getUrl()}</a></p>";
echo "<small style='color:#64748b;'>{$post->getInfoFechas()}</small>";
echo "</div>";
Haz clic para editar este código