Reto - Ejercicio

18/19

Lectura

Practicar es muy importante, ya que te permitirá pulir tus habilidades de desarrollo y te animo a que realices el siguiente reto con todo lo que has aprendido.

...

Regístrate o inicia sesión para leer el resto del contenido.

Aportes 32

Preguntas 0

Ordenar por:

¿Quieres ver más aportes, preguntas y respuestas de la comunidad?

Listo!

Mi estructura de archivos es:

+ Blog: {

    +src: {
        -Author.php
        -Category.php
        -Post.php
        -User.php
    }

    +vendor: { ... }

    -composer.json
    -composer.lock
    -index.php

}

composer.json:

{
    "name": "retaxmaster/post",
    "description": "Proyeto de OOP",
    "autoload": {
        "psr-4": {
            "Blog\\": "src/"
        }
    }
}

Author.php:

<?php

namespace Blog;

class Author extends User {

    protected $created_posts;
    protected $posts = [];

    public function create_post(Post $post) {
        $this->posts[] = $post;
    }

    public function get_postst() : array {
        return $this->posts;
    }

}

?>

Category.php:

<?php

namespace Blog;

class Category {

    protected $name;

    public function set_name(string $name) {
        $this->name = $name;
    }

    public function get_name() : string {
        return $this->name;
    }

}

?>

Post.php:

<?php

namespace Blog;

class Post {

    protected $title;
    protected $content;
    protected $category;

    public function add_category(Category $category) {
        $this->category = $category;
    }

    public function add_title(string $title) {
        $this->title = $title;
    }

    public function add_content(string $content) {
        $this->content = $content;
    }

    public function get_post() : string {
        return "<strong>Título:</strong> $this->title <br> <strong>Contenido:</strong> $this->content <br> <strong>Categoría:</strong> {$this->category->get_name()}";
    }

}

?>

User.php:

<?php

namespace Blog;

class User {

    protected $name;
    protected $last_name;

    public function set_name(string $name, string $last_name) {
        $this->name = $name;
        $this->last_name = $last_name;
    }

    public function get_full_name() : string {
        return $this->name . " " . $this->last_name;
    }

}

?>

index.php:

<?php

include __DIR__ . "/vendor/autoload.php";

use Blog\Author;
use Blog\Category;
use Blog\Post;

// Primero creo las categorías

// Categoría PHP
$php_category = new Category();
$php_category->set_name("PHP");

// Categoría VueJS
$vue_category = new Category();
$vue_category->set_name("VueJS");

// Ahora creo al autor
$retaxmaster = new Author();
$retaxmaster->set_name("Carlos", "Gómez");

// Ahora creo un post sobre PHP
$php_functions_post = new Post();
$php_functions_post->add_title("Post para hablar acerca de funciones en PHP");
$php_functions_post->add_content("En este post hablaremos sobre cómo funcionan las funciones en PHP");
$php_functions_post->add_category($php_category);

// Ahora creo un post sobre VueJS
$vue_app_post = new Post();
$vue_app_post->add_title("Post sobre cómo crear una app con VueJS");
$vue_app_post->add_content("En este post hablaremos sobre qué necesitamos para crear una app con VueJS");
$vue_app_post->add_category($vue_category);

// Ahora le asigno los posts al autor
$retaxmaster->create_post($php_functions_post);
$retaxmaster->create_post($vue_app_post);

// Y por último listamos los posts
$author_post = $retaxmaster->get_postst();

foreach ($author_post as $post) {
    
    echo "El usuario {$retaxmaster->get_full_name()} tiene el siguiente post: <br><br>";
    echo $post->get_post();
    echo "<br><br><br>";

}

?>

It works 😄!

Excelente curso ❤️

Esta es mi solución al reto, agradecería cualquier feedback que me puedan dar:

Aquí está el código: https://github.com/weoka/Poster

Clase User:

<?php

namespace App;

class User
{
    private $name;
    private $email;
    private $password;

    public function setName($name)
    {
        $this->name = $name;
    }

    public function getName()
    {
        return $this->name;
    }

    public function setEmail($email)
    {
        $this->email = $email;
    }

    public function getEmail()
    {
        return $this->email;
    }

    public function setPassword($password)
    {
        $this->password = $password;
    }
}

Clase Author:

<?php

namespace App;
use App\Post;
use App\Category;

class Author extends User
{
    private $posts = [];

    public function setPost(Post $post)
    {
        $this->posts[] = $post;
    }

    public function getPost()
    {
        return $this->posts;
    }

    public function addPost($post)
    {
        array_push($this->posts, $post);
    }

    public function countPosts()
    {
        return count($this->posts);
    }
}

Clase Post:

<?php

namespace App;

class Post
{
    private $title;
    private $content;
    private $category = [];

    public function __construct ($title, $content, Category $category)
    {
        $this->title        = $title;
        $this->content      = $content;
        $this->setCategory($category);
    }

    public function setTitle($title)
    {
        $this->title = $title;
    }

    public function getTitle()
    {
        return $this->title;
    }

    public function setContent($content)
    {
        $this->content = $content;
    }

    public function getContent()
    {
        return $this->content;
    }

    public function setCategory(Category $category)
    {
        array_push($this->category, $category);
    }

    public function getCategory()
    {
        return $this->category;
    }
}

Clase Category:

<?php

namespace App;

class Category
{
    private $name;

    public function __construct($name)
    {
        $this->name = $name;
    }
}

Clase PostTest:

<?php

use PHPUnit\Framework\TestCase;
use App\Author;
use App\Category;
use App\Post;

class PostTest extends TestCase
{
    public function test_post()
    {
        // Creamos un usuario
        $author = new Author();
        // Crear categoría
        $category = new Category("PHP");
        // Crear post
        $post = new Post("Título", "Contenido", $category);
        // Agregar post al autor
        $author->addPost($post);

        // Aserción o afirmación para comprobar que tenemos 1 post agregado
        $this->assertEquals(1, $author->countPosts());
        // Aserción o afirmación para comprobar que la categoría es una instancia de la clase Category
        $this->assertInstanceOf(Category::class, $post->getCategory()[0]);
    }
}

index.php

<?php

require_once "vendor/autoload.php";
use App\Author;
use App\Post;
use App\Category;

// Crear un autor:
$author = new Author();
$author->setName("Carlos Betancourt");
$author->setEmail("[email protected]");
$author->setPassword("mypassword");

// Crear categorías:
$categoryPHP    = new Category("PHP");
$categoryJava   = new Category("Java");
$categoryHTML   = new Category("HTML");

// Crear tres post
$postOne    = new Post("Primer Post","Contenido del primer post.", $categoryPHP, $author);
$postTwo    = new Post("Segundo Post","Contenido del segundo post.", $categoryJava, $author);
$postThree  = new Post("Tercer Post","Contenido del tercer post.", $categoryHTML, $author);

// Agregar otras categorías a cada post
$postOne->setCategory($categoryJava);
$postThree->setCategory($categoryJava);

// Agregar posts al author
$author->addPost($postOne);
$author->addPost($postTwo);

echo "<pre>";
var_dump($author);

Es bienvenido el feedback, saludos!!!

Estructure

Author

Category

Post

User

Test

Reto POO con PHP ✅

user.php

<?php
    
    class User{
        // Nombre completo del usuario
        protected $full_name;

        // Almacena todos los post creados
        protected static $post_created = [];
        public static $random = [];

        // Agrega el objeto post al array post_created
        public function agregarPost(Post $post){
            array_push(User::$post_created, $post);
        }

        // Muestra todos los array creados
        public static function mostrarTodo(){
            echo "<pre>";
                print_r(User::$post_created);
            echo "</pre>";
        }
        

    }

?>

Author.php

<?php

    class Author extends User{
        // Lo usamos como objeto para crear un post
        public $post;        

        // Constructor que crea al User
        public function __construct($full_name){
            $this->full_name = $full_name;
        }

        public function getFullName(){
            return $this->full_name;   
        }
    }
?>

Category.php

<?php

    class Category {

        // Será el arreglo que va a contener todas las categorías
        public static $categorys = [];

        // Muestra todas las categorías creadas
        public static function mostrar(){
            echo "<pre>";
                print_r(Category::$categorys);
            echo "</pre>";
        }
    }

?>

Post.php

<?php

    include("Category.php");

    class Post{

        protected $date_create; // Fecha creada

        public function __construct(private string $full_name, protected $title, protected $comment, private string $category){

            // Establezco la fecha
            $this->date_create = date("d-n-Y");

            // paso a minuscula la categoría
            $category = strtolower($category);

            // Agrego la categoría al array categorys
            if( in_array($category, Category::$categorys) == false){
                array_push(Category::$categorys, $this->category);
            }

            // Se puede añadir desde aquí el post al arreglo de post_created, pero me dio flojera
        }

        public function showPost(){ 
?>
            <!DOCTYPE html>
            <html lang="es">
            <head>
                <meta charset="UTF-8">
                <meta http-equiv="X-UA-Compatible" content="IE=edge">
                <meta name="viewport" content="width=device-width, initial-scale=1.0">
                <title>Mi Post</title>
                <link rel="stylesheet" href="random.css">
            </head>
            <body>

                <section class="main-container">
                    <div class="container">
                        <div class="container-author">
                            <p><?=$this->full_name?></p>
                        </div>
                        <div class="container-date">
                            <!-- <p>05-10-2022</p>  -->
                            <p><?=$this->date_create?></p>
                        </div>
                    </div>

                    <div class="container">
                        <div class="container-title">
                            <p><?=$this->title?></p>
                        </div>
                        <div class="container-category">
                            <p><?=$this->category?></p>
                        </div>
                    </div>
                    

                    <div class="container container-content">
                        <p><?=$this->comment?></p>    
                    </div>
                </section>
                
            </body>
            </html>
<?php  
        }
    }

?>



index.php

<?php
    include("User.php");
    include("Author.php");
    include("Post.php");

    // Primero creo al author quien es un usuario 
    $Akeneth = new Author("Keneth Lopez Izaguirre"); // objeto "Akeneth" de la clase "Author"
    $AMaria = new Author("Maria Angelica Del Sol"); // objeto "AMaria" de la clase "Author"
    $APablo = new Author("Pablo Quispe Mamani"); // objeto "APablo" de la clase "Author"
    
    // Creo el post
    // Creo el post con el atributo post
    $Akeneth->post = new Post(
        $Akeneth->getFullName(), 
        "Mi primer título", 
        "Content: Lorem ipsum dolor sit, amet consectetur adipisicing elit. Nam, asperiores, sint libero, quisquam nesciunt minus placeat iure neque tempore quidem earum velit ducimus commodi a nobis aspernatur? Quam, odio ut!", 
        "VueJS");
    // Agrego todo el objeto al array posts
    $Akeneth->agregarPost($Akeneth->post);

    $AMaria->post = new Post(
        $AMaria->getFullName(), 
        "Saludando", 
        "Content: Lorem ipsum dolor sit, amet consectetur adipisicing elit. Nam, asperiores, sint libero, quisquam nesciunt minus placeat iure neque tempore quidem earum velit ducimus commodi a nobis aspernatur? Quam, odio ut!", 
        "PHP");
    // Agrego todo el objeto al array posts
    $AMaria->agregarPost($AMaria->post);  

    $APablo->post = new Post(
        $APablo->getFullName(),
        "Esto es otro título",
        "Esto es el contenido de todo el post, lo mismo que lo anterior pero más corto",
        "Mensaje random");
    // Agrego todo el objeto al array posts
    $APablo->agregarPost($APablo->post);  

    // Muestro el post
    echo $Akeneth->post->showPost();
    echo $AMaria->post->showPost();
    echo $APablo->post->showPost();

    // Lo siguiente es solo para debuguear 
    // Category::mostrar();
    // User::mostrarTodo();
?>

###style.css

@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@200;400&display=swap');

*{
    box-sizing: border-box; 
    margin: 0; 
    padding: 0;
}

:root {
    --color-text: #f3f3f3;
    --primary-color: #f7931a;
    --secondary-color: white;
    --principal-font: 'Poppins', sans-serif;
}
html{
    font-size: 62.5%; /* 1rem = 10px */
    font-family: var(--principal-font);
}


.main-container{
    width: 600px;
    height: auto;
    margin: 0 auto;
    margin-top: 30px;
    padding: 10px;
    display: flex;
    flex-direction: column;
    align-items: center;
    background-color:  var(--primary-color);
    border-radius: 1rem;
    box-shadow: 0px 4px 8px rgb(89 73 30 / 16%);
}

.container{
    display: flex;
    width: 100%;
    padding: 5px;
}
.container-author{
    display: inline-block;
    margin-right: 15px;
    font-size: 1.8rem;
    font-weight: bold;
}

.container-date{
    display: inline-block;
    font-size: 1.8rem;
}

.container-title{
    color: var(--secondary-color);
    font-size: 1.5rem;
    margin-right: 15px;
    font-weight: bold;
}

.container-category{
    color: var(--secondary-color);
    font-size: 1.2rem;
    border-radius: 1rem;
    box-shadow: 1px 1px 2px rgba(128, 128, 128, 0.5);
    padding: 3px 5px;
    background-color: white;
    color: black;
}

.container-content{
    color: var(--secondary-color);
    font-size: 1.5rem;
    text-align: justify;
}

Así quedó mi proyecto

User.php

<?php

namespace App;

class User
{
    public $nombre;
    protected $password;

    public function __construct($nombre, $password = 'defaultPassword')
    {
        $this->nombre = $nombre;
        $this->password = $password;
    }
}

Author.php

<?php 

namespace App;

class Author extends User
{
    public $amount_of_posts = 0;

    public function addAmountOfPost()
    {
        $this->amount_of_posts = $this->getAmountOfPost() + 1;
    }

    public function getAmountOfPost()
    {
        return $this->amount_of_posts;
    }
}

Comment.php

<?php

namespace App;

class Comment
{
    protected $likes;
    protected $comment;

    public function __construct($comment)
    {
        $this->comment = $comment;
        $this->likes = 0;
    }
}

Category.php

<?php

namespace App;

class Category
{
    public $name;

    public function __construct($name)
    {
        $this->name = $name;
    }
}

Post.php

<?php

namespace App;

class Post
{
    protected $comments = [];
    protected $author;
    protected $category;
    protected $title;
    protected $content;
    protected $views = 0;
    protected $tags = [];

    public function addComment(Comment $comment)
    {
        $this->comments[] = $comment;
    }

    public function countComments()
    {
        return count($this->comments);
    }

    public function getComments()
    {
        return $this->comments;
    }

    public function addAuthor(Author $author)
    {
        $this->author = $author;
        $author->addAmountOfPost();
    }

    public function getAuthor()
    {
        return $this->author;
    }

    public function addCategoty(Category $category)
    {
        $this->category = $category;
    }

    public function getCategory()
    {
        return $this->category;
    }

    public function addTittle($title)
    {
        $this->title = $title;
    }

    public function addContent($content)
    {
        $this->content = $content;
    }

    public function getViews()
    {
        return $this->views;
    }

    public function addView()
    {
        $this->views = $this->getViews() + 1;
    }

    public function addTag($tag)
    {
        $this->tags[] = $tag;
    }

    public function countTags()
    {
        return count($this->tags);
    }

    public function getTags()
    {
        return $this->tags;
    }
}

index.php

<?php

require __DIR__ . '/vendor/autoload.php';

use App\Author;
use App\Category;
use App\Comment;
use App\Post;

$author = new Author("Gustavo");
$category = new Category("PHP");
$post = new Post();
$comment = new Comment("Muy bueno, gracias");

$post->addComment($comment);
$post->addAuthor($author);
$post->addCategoty($category);
$post->addTittle("Introducción a PHP");
$post->addContent("PHP es un lenguaje de programación Orientado a Objetos");
$post->addView();
$post->addTag("Programación");
$post->addTag("Backend");

echo '<pre>';
echo var_dump($post);
echo '</pre>';
<?php

use PHPUnit\Framework\TestCase;
use App\Post;
use App\Comment;
use App\Author;
use App\Category;

class PostTest extends TestCase
{

    public function testCreatePost(){
        $author = new Author("Saul");
        $category = new Category("PHP");
        $post = new Post();

        $post->create($author, $category, 'content');

        $this->assertEquals(1, $post->getCountPostByAuthor($author));
        $this->assertEquals(1, $post->getCountPostByCategory($category));

    }

    public function testAddCommentToPost(){
        $post = new Post();
        $author = new Author("Saul");
        $comment = new Comment();

        $post->addComment($author, $comment);

        $this->assertEquals(1, $post->countComments());
        $this->assertInstanceOf(Comment::Class, $post->getComments()[0]['comment']);

    }
}


<?php

namespace App;

use App\User;

class Author extends User{

    public function __construct($name)
    {
        parent::__construct($name);
    }

}
<?php

namespace App;

class Category{

    private $name;

    public function __construct($name){

        $this->name = $name;

    }

    public function getName(){

        return $this->name;
    }

}
<?php

namespace App;

class Post{

    private $comments=[];
    private $articles=[];


    public function create(Author $author, Category $category, $content){

        $this->articles[] = ["author" => $author->getName(),
        "category" => $category->getName(), 
        "content" => $content ];
        
    }


    public function getCountPostByAuthor(Author $author){

        return  count(array_map(function($item) use($author){
            return $item['author'] == $author->getName();
            }
        ,$this->articles ));

    }
        
    public function getCountPostByCategory(Category $category){


        return  count(array_map(function($item) use($category){
            return $item['category'] == $category->getName();
            }
        ,$this->articles ));

    }

    public function addComment(Author $author,Comment $comment){

        $this->comments[] = ["author" => $author->getName(),
            "comment" => $comment];

    }

    public function countComments(){

        return count ($this->comments);

    } 

    public function getComments(){

        return $this->comments;
    }

}
<?php

namespace App;

class User{

    private $name;

    public function __construct($name)
    {
        $this->name = $name;

    }

    public function getName(){
        return $this->name;
    }

}

resultado

composer.json

{
    "name": "slasher/project",
    "description": "just a simple project",
    "autoload": {
        "psr-4": {
            "App\\": "src/"
        }
    },
    "require-dev": {
        "phpunit/phpunit": "^9.5"
    }
}

AuthorTest

<?php

use PHPUnit\Framework\TestCase;
use App\Author;

class AuthorTest extends TestCase
{
    public function test_add_author()
    {
        $author = new Author('197O00045', 'Alexis','Vazquez','Morales', true);

        $this->assertInstanceOf(Author::class, $author);
    }
}

CategoryTest

<?php

use PHPUnit\Framework\TestCase;
use App\Category;

class CategoryTest extends TestCase
{
    public function test_add_category()
    {
        $cateogry = new Category('1','PHP');

        $this->assertInstanceOf(Category::class, $cateogry);
    }
}

PostTest

<?php

use PHPUnit\Framework\TestCase;
use App\Post;

class PostTest extends TestCase
{
    public function test_add_post()
    {
        $post = new Post(1, 'este es un nuevo post', '197O00045', '1');

        $this->assertInstanceOf(Post::class, $post);

    }
}

UserTest

<?php

use PHPUnit\Framework\TestCase;
use App\User;

class UserTest extends TestCase
{
    public function test_add_user()
    {
        $user = new User('Alexis','Vazquez','Morales');

        $this->assertInstanceOf(User::class, $user);
    }
}

El reto esta genial, lo solucione a mi manera y conforme lo que llegue a aprender en los cursos que fue bastante. Reconozco que me falta mucho por mejorar y aprender. Les comparto mi repositorio con el reto y les prometo que volveré para resolver toda la deuda técnica que deje en el reto. Saludos.

https://github.com/albertusortiz/reto_poo_php/tree/master

Reto Completado ;D

Estructura de carpetas y archivos

Author.php


User.php

Category.php

Comment.php

Post.php


Super!, a practicar lo aprendido

Ahora vamos por el examen …

Comparto mi solución al reto:

Estructura de archivos

Post.php

namespace App;

class Post 
{
    protected $comments = [];
    protected $title;
    protected $description;

    public function __construct (string $title, string $description)
    {
        $this->title = $title;
        $this->description = $description;
    }

    public function addComment(Comment $comment)
    {
        $this->comments[] = $comment;
    }

    public function countComments()
    {
        return count($this->comments);
    }

    public function getComments()
    {
        return $this->comments;
    }

    public function getTitle()
    {
        return $this->title;
    }

    public function getDescription()
    {
        return $this->description;
    }
}

Category.php

namespace App;

class Category
{
    private $name;

    public function __construct (string $name)
    {
        $this->name = $name;
    }

    public function getName ()
    {
        return $this->name;
    }
}

User.php

namespace App;

class User
{
    protected $firstName;
    protected $lastName;

    public function __construct(string $firstName, string $lastName)
    {
        $this->firstName = $firstName;
        $this->lastName = $lastName;
    }

    public function getFirstName ()
    {
        return $this->firstName;
    }

    public function getLastName ()
    {
        return $this->lastName;
    }
}

Author.php

namespace App;

class Author extends User
{
   protected $createdPosts = [];

   public function writePost (Post $post)
   {
        array_push($this->createdPosts, $post);
   }

   public function countCreatedPosts ()
   {
      return count($this->createdPosts);
   }

   public function getCreatedPosts ()
   {
      return $this->createdPosts;
   }
}

index.php

<?php
include './vendor/autoload.php';

use App\Author;
use App\Category;
use App\Post;

// Creo al autor del post
$author = new Author('Nestor', 'Velasquez');

// Creo una categoría de ciencias
$scienceCategory = new Category('Ciencias');

// Creo una categoría de Programación
$programmingCategory = new Category('Programacion');

// Creo un primer post
$firstPost = new Post('Las ciencias de la vida', 'La vida es una cienca y la ciencia es una vida... Eres lo que vives, somos ellos, somos aquellos, somos los hombres de negro');

// Creo otro post
$secondPost = new Post('Cómo ser un hacker con Python', 'Para ser un hacker en python tienes que ser un crack en python primero... asi como yo que soy un super crack');

// Mensaje de bienvenida al usuario autor
echo "<h2>Bienvenido {$author->getFirstName()} {$author->getLastName()}</h2>";

// Le asigno un autor a los post creados
$author->writePost($firstPost);
$author->writePost($secondPost);

echo "<p>Has creado hasta ahora {$author->countCreatedPosts()} Posts</p>";

echo "<p>Tus Posts creados son: </p>";

echo "<table>";
    for ($i=0; $i < $author->countCreatedPosts(); $i++) {
        echo "<tr>";
        echo "<td><h4>{$author->getCreatedPosts()[$i]->getTitle()}</h4>
                    <p>{$author->getCreatedPosts()[$i]->getDescription()}</p>
            </td>";
        echo "</tr>";
    }

Comparto mi solución

Estructura de Carpetas

User.php

<?php

namespace App;

class User {
    protected $name;
    public function __construct($name)
    {
        $this->name = $name;
    }
}

Author.php

<?php 
namespace App;

use App\User;

class Author extends User 
{

}

Category.php

<?php
namespace App; 

class Category 
{
    protected $name;
    
    public function __construct($name)
    {  
        $this->name = $name;
    }
}

Comment.php

<?php 

namespace App;

class Comment 
{
    
}

Post.php

<?php

namespace App;

class Post 
{
    protected $comments = [];
    public $author;
    public $category;

    public function addComment(Comment $comment){
        $this->comments[] = $comment;
    }

    public function countComments(){
        return count($this->comments);
    }

    public function getComments(){
        return $this->comments;
    }
}

PostTest.php

<?php 
use PHPUnit\Framework\TestCase;
use App\Author;
use App\Post;
use App\Category;

class PostTest extends TestCase
{
    public function test_create_post(){
        $author = new Author('Francisco');
        $category = new Category('PHP');
        $post = new Post();
        $post->author = $author;
        $post->category = $category;        
        
        $this->assertInstanceOf(Author::class, $author);
        $this->assertInstanceOf(Category::class, $category);
        $this->assertInstanceOf(Post::class, $post);
        $this->assertClassHasAttribute('author', Post::class);
        $this->assertClassHasAttribute('category', Post::class);
        $this->assertInstanceOf(Author::class, $post->author);
        $this->assertInstanceOf(Category::class, $post->category);
    }
}

index.php

<?php
include './vendor/autoload.php';

use App\Post;
use App\Author;
use App\Category;

$author = new Author('Francisco');
$category = new Category('PHPUnit');
$post = new Post();
$post->author = $author;
$post->category = $category;

print_r($post);

El test asociado podría ser algo así: ```js use PHPUnit\Framework\TestCase; use App\Post; use App\Comment; use App\User; use App\Author; use App\Category; class Ejercicio18Test extends TestCase { public function test_user_and_author() { $author = new Author('john.doe'); $this->assertEquals('john.doe', $author->name()); } public function test_add_categories() { $category = new Category('PHP Code'); $comment = new Comment(); $comment->addCategory($category); // Las categorias deben asociarse a un slug basado en el texto original $this->assertEquals('php-code', $category->slug()); } } ```
Reto completado. les dejo el link del repositorio en git hub. <https://github.com/Diego-Cundapi/PHP-POO/tree/main/retoDelCurso> Tengo que decir que si me llevo sus dos horitas por que salieron muchos errores, y aunque implemente un poco de test no supe hacer algunos test pero espero en siguiente cursos aprender más. Exito a todos. resultado: ![](https://static.platzi.com/media/user_upload/image-3cb599e9-b555-40d8-80f3-5e98a7d7b093.jpg)

Mi código es:

User.php:

<?php 

namespace App; 

class User{

    protected $username; 

    public function __construct($username) {
        $this->username = $username;
    }

    public function getUsername() {
        return $this->username;
    }

}

Category:

<?php 

namespace App; 

class Category{
    protected $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

Author:

<?php 

namespace App;
use App\User; 

class Author extends User{

    public function createPost($title, $content, $categories) {
        return new Post($this, $title, $content, $categories);
    }

}

Post:

<?php 

namespace App; 

class Post{

    protected $author;
    protected $title;
    protected $content;
    protected $categories;

    public function __construct($author, $title, $content, $categories) {
        $this->author = $author;
        $this->title = $title;
        $this->content = $content;
        $this->categories = $categories;
    }

    public function getAuthor() {
        return $this->author;
    }

    public function getTitle() {
        return $this->title;
    }

    public function getContent() {
        return $this->content;
    }

    public function getCategories() {
        return $this->categories;
    }

}

index:

<?php 

include __DIR__ . "/vendor/autoload.php";

use App\Author;
use App\Category;
use App\Post;

$author = new Author("JohnDoe");
$post = $author->createPost(
    "Introducción a PHP",
    "PHP es un lenguaje de programación de propósito general ampliamente utilizado para el desarrollo web.",
    [new Category("PHP"), new Category("Desarrollo Web")]
);

echo "Autor: " . $post->getAuthor()->getUsername() . "\n";
echo "Título: " . $post->getTitle() . "\n";
echo "Contenido: " . $post->getContent() . "\n";
echo "Categorías: ";
foreach ($post->getCategories() as $category) {
    echo $category->getName() . ", ";
}
```js // User.php class User { protected $name; protected $email; public function __construct($name, $email) { $this->name = $name; $this->email = $email; } public function getName() { return $this->name; } public function getEmail() { return $this->email; } } // Author.php class Author extends User { public function createPost($title, $content, $categories) { return new Post($this, $title, $content, $categories); } // Post.php class Post { protected $author; protected $title; protected $content; protected $categories; public function __construct($author, $title, $content, $categories) { $this->author = $author; $this->title = $title; $this->content = $content; $this->categories = $categories; } public function getAuthor() { return $this->author; } public function getTitle() { return $this->title; } public function getContent() { return $this->content; } public function getCategories() { return $this->categories; } } // Category.php class Category { protected $name; public function __construct($name) { $this->name = $name; } public function getName() { return $this->name; } } // index.php (ejemplo de uso) // Incluir las clases require_once 'User.php'; require_once 'Author.php'; require_once 'Post.php'; require_once 'Category.php'; // Crear un usuario $user = new User('Juan', '[email protected]'); // Crear un autor (que es un usuario) $author = new Author('Pedro', '[email protected]'); // Crear categorías $category1 = new Category('PHP'); $category2 = new Category('Vue.js'); $category3 = new Category('JavaScript'); // Crear un post $post = $author->createPost('Título del Post', 'Contenido del post...', [$category1, $category3]); // Mostrar información del post echo "Autor: " . $post->getAuthor()->getName() . "\n"; echo "Título: " . $post->getTitle() . "\n"; echo "Contenido: " . $post->getContent() . "\n"; echo "Categorías: "; foreach ($post->getCategories() as $category) { echo $category->getName() . ", "; } ```User.php phpCopiar`class User` { ` protected $name`; ` protected $email`; ` public function __construct($name, $email`) ` `{ ` $this->name = $name`; ` $this->email = $email`; } ` public function getName(`) ` `{ ` return $this`->name; } ` public function getEmail(`) ` `{ ` return $this`->email; } } Auth
Comparto mi aporte <https://github.com/fua94/Platzi-PHP-POO-challenge>

Mi estructura de archivos es:

+ Blog: {

    +src: {
        -Autor.php
        -Category.php
        -Post.php
        -User.php
    }

    +vendor: { ... }

    -composer.json
    -composer.lock
    -index.php

}

Composer.json

{
  "name": "jonathanurdaneta/post",
  "description": "Proyecto de OOP",
  "autoload": {
    "psr-4": {
      "App\\": "src/"
    }
  }
}

Autor.php

<?php

namespace App;

class Autor extends User
{
  private array $posts = [];

  public function addNew_post(Post $newPost) {
    $this->posts[] = $newPost;
  }

  public function getPosts():array {
    return $this->posts;
  }

  public function getAuthor():string {
    return $this->full_name;
  }
}

Category.php

<?php

namespace App;

class Category
{
  protected string $title_category = '';

  public function getCategory_title() {
    return $this->title_category;
  }
}

Post.php

<?php

namespace App;

class Post extends Category
{
  private string $title_post = '';
  private string $article_post = '';

  public function __construct(string $titlePost, string $articlePost, string $categoryPost)
  {
    $this->title_post = $titlePost;
    $this->article_post = $articlePost;
    $this->title_category = $categoryPost;
  }

  public function getPost_name():string {
    return ('Titulo: '. $this->title_post);
  }

  public function getPost_parahraph():string {
    return ('Articulo: '. $this->article_post);
  }
}

User.php

<?php

namespace App;

class User
{
  protected string $user_name = '';
  protected string $full_name = '';

  public function __construct($userName, $fullName)
  {
    $this->user_name = $userName;
    $this->full_name = $fullName;
  }

  public function getName():string {
    return $this->full_name;
  }

  public function getUser():string {
    return $this->user_name;
  }
}

index.php

<?php

include __DIR__ . "/vendor/autoload.php";

use App\Autor;
use App\Post;

// POST JAVASCRIPT
// Primero creamos el post
$post_javascript = new Post('Actualizaciones de Javascript 2023', "Javascript ha sido actualziado para mejorar sun funciones. Descubre mas aqui", "javascript");

// Ahora creamos el author, usuario y le asignamos el post
$author_john = new Autor("johnmub", "Jonathan Urdaneta");
$author_john->addNew_post($post_javascript);

// POST PHP
// Primero creamos el post
$post_php = new Post('PHP aun tiene futuro', "Con los nuevos framework php si tiene futuro", "php");

// Ahora creamos el author, usuario y le asignamos el post
$author_harper = new Autor("harperU", "Harper Urdaneta");
$author_harper->addNew_post($post_php);

// POST REACT
// Primero creamos el post
$post_react = new Post('React obseleto', "Con nextjs React ha quedado en el olvido ajjaa", "reactjs");

// segundo post
$post_nextjs = new Post('Nextjs nueva tecnologia', "Esta tecnologia sirve para Web3", "nextjs");

// Ahora creamos el author, usuario y le asignamos el post
$author_dairy = new Autor("dairyM", "Dairy Medina");
// Agregamos los 2 post
$author_dairy->addNew_post($post_react);
$author_dairy->addNew_post($post_nextjs);


// Ahora vamos a listar todos los post
// Los pos de johnmub
$getJohn = $author_john->getPosts();

echo ("El author: {$author_john->getAuthor()} ha escrito ".count($getJohn)." posts. Estos son:<br><br>");

foreach ($getJohn as $key => $post) {
  echo ($post->getPost_name()." - ".$post->getPost_parahraph()." - Categoria: ".$post->getCategory_title()."<br><br>");
}

// Los post de harperU
$getHarper = $author_harper->getPosts();

echo ("El author: {$author_harper->getAuthor()} ha escrito ".count($getHarper)." posts. Estos son:<br><br>");

foreach ($getHarper as $key => $post) {
  echo ($post->getPost_name()." - ".$post->getPost_parahraph()." - Categoria: ".$post->getCategory_title()."<br><br>");
}

// Lost post de dairyM
$getDairy = $author_dairy->getPosts();

echo ("El author: {$author_dairy->getAuthor()} ha escrito ".count($getDairy)." posts. Estos son:<br><br>");

foreach ($getDairy as $key => $post) {
  echo ($post->getPost_name()." - ".$post->getPost_parahraph()." - Categoria: ".$post->getCategory_title()."<br><br>");
}

Excelente Curso

PD: Use spanglish
PD: Siempre uso nombres de mi familia

Mi Reto


<?php

require 'vendor/autoload.php';

use App\Author;
use App\Post;
use App\Category;

$author = new Author("Jehison",29);
$category = new Category("PHP");
$post = new Post($author,"Primer post",$category);

$post->addPost($post);

Mi solucion al reto

Author.php

<?php

namespace App;

class Author extends User {}

Category.php

<?php

namespace App;
class Category
{
    public $name;

    public function __construct($name)
    {
        $this->name = $name;
    }
}

Comment.php

<?php

namespace App;
class Comment {}

Post.php

<?php

namespace App;
class Post 
{
    protected $comments = [];
    private $author;
    protected $categories = [];

    public function __construct(Author $author)
    {
        $this->author = $author;
    }

    public function getAuthor()
    {
        return $this->author;
    }

    public function addComment(Comment $comment)
    {
        $this->comments[] = $comment;
    }

    public function countComments()
    {
        return count($this->comments);
    }

    public function getComments()
    {
        return $this->comments;
    }

    public function addCategory(Category $category)
    {
        $this->categories[] = $category;
    }

    public function getCategories()
    {
        return $this->categories;
    }
}

User.php

<?php
namespace App;
class User
{
    private $username;
    private $password;

    public function __construct($username, $password)
    {
        $this->username = $username;
        $this->password = $password;
    }
}

PostTest.php

<?php

use PHPUnit\Framework\TestCase;
use App\Post;
use App\Comment;
use App\Author;
use App\Category;

class PostTest extends TestCase
{
    public function test_author()
    {
        $username = "testusername";
        $password = "testpassword";
        $author = new Author($username, $password);
        $post = new Post($author);

        $this->assertInstanceOf(Author::class, $post->getAuthor());
    }

    public function test_add_comment_to_post()
    {
        $username = "testusername";
        $password = "testpassword";
        $author = new Author($username, $password);
        $post = new Post($author);
        $comment = new Comment();

        $post->addComment($comment);

        $this->assertEquals(1, $post->countComments());
        $this->assertInstanceOf(Comment::class, $post->getComments()[0]);
    }

    public function test_add_categories()
    {
        $username = "testusername";
        $password = "testpassword";
        $author = new Author($username, $password);
        $post = new Post($author);

        $category1Name = "Javascript";
        $category1 = new Category($category1Name);

        $category2Name = "PHP";
        $category2 = new Category($category2Name);

        $post->addCategory($category1);
        $post->addCategory($category2);

        $this->assertEquals(2, count($post->getCategories()));
        $this->assertInstanceOf(Category::class, $post->getCategories()[0]);
    }
}

Un buen ejercicio para practicar. Explicare mi solucion, quizas les pueda ayudar en algo.

Mi idea era al final obtener desde index.php obtener todo el objeto de post que corrobora la existencia dentro de una instancia de author y category. Recordemos que un post tiene esas dos caracteristicas.

Para ello implemente una interfaz llamada PostInterface que, por buena practica me obligar a ‘‘setear’’ el author y la category como instancias. Y lo demas fue hacer uso de constructores y herencia para el comportamiento inicial.

index.php

<?php

namespace App;

require("./Author.php");
require("./Category.php");
require("./Post.php");


$author = new Author(1, 
"[email protected]", 
"[email protected]", 
"Carlos", "Sanjuan");

$category = new Category(1, "PHP");

$post = new Post(1,
"My first post",
"This is my first post",
"2020-01-01",
"2020-01-01");
$post->setAuthor($author);
$post->setCategory($category);



echo "<pre>";
print_r($author);
echo "<pre>";
print_r($user);
echo "<pre>";
print_r($category);
echo "<pre>";
print_r($post);
<?php

namespace App;

require("./User.php");

class Author extends User
{
    private $name;
    private $lastname;

    public function __construct($id, $email, $password, $name, $lastname)
    {
        parent::__construct($id, $email, $password);
        $this->name = $name;
        $this->lastname = $lastname;
    }

}
<?php 

namespace App;

class User 
{
    protected $id;
    protected $email;
    protected $password;

    public function __construct($id, $email, $password)
    {
        $this->id = $id;
        $this->email = $email;
        $this->password = $password;
    }
    
}
<?php 

namespace App;

require("./PostInterface.php");

class Post implements PostInterface 
{
    protected $id;
    protected $title;
    protected $content;
    protected $author;
    protected $category;
    protected $created_at;
    protected $updated_at;

    public function __construct($id, $title, $content,$created_at, $updated_at)
    {
        $this->id = $id;
        $this->title = $title;
        $this->content = $content;
        $this->created_at = $created_at;
        $this->updated_at = $updated_at;
    }

    public function setAuthor(Author $author)
    {
        $this->author = $author;
    }

    public function setCategory(Category $category)
    {
        $this->category = $category;
    }
    
}
<?php

namespace App;

Interface PostInterface 
{
    public function setAuthor(Author $author);
    public function setCategory(Category $category);
}
<?php

namespace App;

class Category 
{
    public $id;
    public $name;

    public function __construct($id, $name)
    {
        $this->id = $id;
        $this->name = $name;
    }
}

Para al final tener esta salida:

App\Author Object
(
    [id:protected] => 1
    [email:protected] => carlosdsanjuan@outlook.com
    [password:protected] => carlosdsanjuan@outlook.com
    [name:App\Author:private] => Carlos
    [lastname:App\Author:private] => Sanjuan
)
App\Category Object
(
    [id] => 1
    [name] => PHP
)
App\Post Object
(
    [id:protected] => 1
    [title:protected] => My first post
    [content:protected] => This is my first post
    [author:protected] => App\Author Object
        (
            [id:protected] => 1
            [email:protected] => carlosdsanjuan@outlook.com
            [password:protected] => carlosdsanjuan@outlook.com
            [name:App\Author:private] => Carlos
            [lastname:App\Author:private] => Sanjuan
        )

    [category:protected] => App\Category Object
        (
            [id] => 1
            [name] => PHP
        )

    [created_at:protected] => 2020-01-01
    [updated_at:protected] => 2020-01-01
)

Excelente practica.

La clase User la declare como abstracta para que no sea instanciada sino solo heredada.

<?php

namespace Reto;

abstract class User
{
    protected $name, $last_name;

    public function __construct($name, $last_name)
    {
        $this->name = $name;
        $this->last_name = $last_name;
    }

    abstract public function getInfo();
}

Las Clase Author utiliza el constructor del padre pero implemente el propio para agregar otra información.

<?php

namespace Reto;

class Author extends User
{
    protected $type;
    protected $posts = array();

    public function __construct($name, $last_name)
    {
        parent::__construct($name, $last_name);
        $this->type = 'Author';
    }

    public function getInfo() :string
    {
        return "Hello {$this->name} {$this->last_name}, i hope you are very well today. Author type: {$this->type}";
    }

    public function addPost(Post $post)
    {
        $this->posts[] = $post;
    }

    public function getPost() :array
    {
        return $this->posts;
    }
}

My clase post

<?php

namespace Reto;

class Post
{
    public $title, $description, $category, $author;

    public function __construct(Category $category)
    {
        $this->category = $category;
    }

    public function addTitle($title)
    {
        $this->title = $title;
    }

    public function addDescription($description)
    {
        $this->description = $description;
    }

    public function hasTitle() :bool
    {
        return isset($this->title);
    }

    public function hasDescription() :bool
    {
        return isset($this->description);
    }

    public function getCategory()
    {
        return $this->category;
    }
}

Clase Categoría

<?php

namespace Reto;

class Category
{
    protected $nameCategory;

    public function __construct($name)
    {
        $this->nameCategory = $name;
    }
}

Las pruebas:

<?php

use PHPUnit\Framework\TestCase;
use Reto\User;
use Reto\Author;
use Reto\Category;
use Reto\Post;

class PostTest extends TestCase
{
    public function test_post()
    {
        $author = new Author('Fabian', 'Beltran');
        $category = new Category('PHPUnit');
        $post = new Post($category);
        $post->addTitle('Testing whit PHPUnit');
        $post->addDescription(" It's necesary that you put the information here ");
        $author->addPost($post);

        $this->assertEquals(1, $post->hasTitle());
        $this->assertEquals(1, $post->hasDescription());
        $this->assertInstanceOf(Category::class, $post->getCategory());
        $this->assertInstanceOf(Post::class, $author->getPost()[0]);

    }
}

Buenas! Dejo el repositorio en el cual desarrollé el reto, saludos!

<?php

require __DIR__ . '/vendor/autoload.php';

use App\Author;
use App\Category;
use App\Post;
use App\Comment;

$post = new Post;

$post->addComment(new Comment("text",new Author("J. Alen","ABC123"),new Category("PHP")));
$post->addComment(new Comment("text",new Author("X. Perry","OPQ789"),new Category("Vue")));
$post->addComment(new Comment("text",new Author("P. Jhons","XYZ654"),new Category("Javascript")));

echo "Cantidad comentarios: {$post->countComments()}";

Hola, este es mi reto, estoy abierto a opiniones acerca del código

composer.json

{
    "name": "chrisvarg/post",
    "description": "proyecto Post",
    "autoload": {
        "psr-4": {
            "App\\": "src/"
        }
    }   
}

User.php

<?php

namespace App;

class User
{
    protected $name;
    protected $lastName;
    
    /**
     * Get the value of lastName
     */ 
    public function getLastName()
    {
        return $this->lastName;
    }

    /**
     * Set the value of lastName
     *
     * @return  self
     */ 
    public function setLastName($lastName)
    {
        $this->lastName = $lastName;

        return $this;
    }

    /**
     * Get the value of name
     */ 
    public function getName()
    {
        return $this->name;
    }

    /**
     * Set the value of name
     *
     * @return  self
     */ 
    public function setName($name)
    {
        $this->name = $name;

        return $this;
    }
}

Autor.php

<?php

namespace App;

class Autor extends User
{
    protected $post = [];

    public function createPost(Post $post)
    {
        $this->post[] = $post;
    }

    public function getPost()
    {
        return $this->post;
    }
}

Category.php

<?php

namespace App;

class Category
{
    protected $name;

    /**
     * Get the value of name
     */ 
    public function getName()
    {
        return $this->name;
    }

    /**
     * Set the value of name
     *
     * @return  self
     */ 
    public function setName($name)
    {
        $this->name = $name;

        return $this;
    }
}

Post.php

<?php

namespace App;

class Post
{
    protected $title;
    protected $content;
    protected $category;

    /**
     * Get the value of title
     */ 
    public function getTitle()
    {
        return $this->title;
    }

    /**
     * Set the value of title
     *
     * @return  self
     */ 
    public function setTitle(string $title)
    {
        $this->title = $title;
        return $this;
    }

    /**
     * Get the value of content
     */ 
    public function getContent()
    {
        return $this->content;
    }

    /**
     * Set the value of content
     *
     * @return  self
     */ 
    public function setContent(string $content)
    {
        $this->content = $content;

        return $this;
    }

    /**
     * Get the value of category
     */ 
    public function getCategory()
    {
        return $this->category;
    }

    /**
     * Set the value of category
     *
     * @return  self
     */ 
    public function setCategory(Category $category)
    {
        $this->category = $category;

        return $this;
    }

    public function showPost() : string
    {
        return "Title: {$this->getTitle()}
                Content: {$this->getContent()}
                Category: {$this->category->getName()}";
    }
}

index.php

<?php

require_once __DIR__."/vendor/autoload.php";

use App\User;
use App\Autor;
use App\Category;
use App\Post;

// User
$autor = new Autor();
$autor->setName('David');
$autor->setLastName('Vargas');

// Category
$category = new Category();
$category->setName('Laravel');

// Post
$post = new Post();
$post->setTitle('Titulo de un post sobre Laravel');
$post->setContent('Contenido de un post sobre Laravel');
$post->setCategory($category);

$autor->createPost($post);

$posts = $autor->getPost();

foreach ($posts as $post) {
    
    echo $post->showPost();

}

Result

<?php
include “Clases/User.php”;
include “Clases/Author.php”;
include “Clases/Post.php”;
include “Clases/Category.php”;

$user = new Post;
$cate = new Category;
$user->type = new Author();
echo $user->type->getName(‘Sebas’);
echo "<br>categoria: ".$cate->category;

Mi solución al reto:

Como dijeron varios compañeros, se acepta el feedback con gusto.

index.php

<?php

require_once("vendor/autoload.php");

use App\Author;
use App\Category;
use App\Post;

//Nuevo Autor
$author = new Author('Angelica', 'Estupiñan', 'Koala');

//Nueva Categoría
$category = new Category(['arte','lettering']);

//Nuevo post
$post = new Post('Como crear plantillas con lettering','Aplica nuevas tecnicas', $author, $category);

print_r($post->getAuthor()->getFullname());
echo '</br>';
print_r($post->getCategory()->getCategoryName());
echo '</br>';
print_r($post->getTitle());
echo '</br>';
print_r($post->getContent());

User.php

<?php

namespace App;

abstract class User {
    
    protected $name;
    protected $lastname;
    protected $alias;

    public function __construct(string $name, string $lastname, string $alias)
    {
        $this->name = $name;
        $this->lastname = $lastname;
        $this->alias = $alias;
    }

    public function getName()
    {
       return $this->name;
    }

    public function getLastname()
    {
        return $this->lastname;
    }

    public function getAlias()
    {
        return $this->alias;
    }

    public function getFullname()
    {
        return "{$this->name} {$this->lastname}";
    }
}

Author.php

<?php

namespace App;

class Author extends User
{
    protected $posts = [];
    
    public function __construct($name, $lastname, $alias)
    {
        parent::__construct($name, $lastname, $alias);
    }

    public function setPost(Post $post)
    {
        array_push($this->posts, $post);
    }

    public function getPosts()
    {
        return $this->posts;
    }

    public function getCountPosts()
    {
        return count($this->posts);
    }
}

Category.php

<?php

namespace App;

class Category
{
    protected $categoryName = [];

    public function __construct(array $categoryName)
    {
        $this->categoryName[] = $categoryName;
    }

    public function getCategoryName()
    {
        return $this->categoryName;
    }
}

Unit tests

AuthorTest.php

<?php

use PHPUnit\Framework\TestCase;

class AuthorTest extends TestCase
{
    public function test_it_can_get_author_attributes()
    {
        $author = new \App\Author('Cristian', 'Garcia', 'Nseiken');
       
        $this->assertEquals('Cristian', $author->getName());
        $this->assertEquals('Garcia', $author->getLastname());
        $this->assertEquals('Nseiken', $author->getAlias());
    }

    public function test_it_can_get_author_fullname()
    {
        $author = new \App\Author('Cristian', 'Garcia', 'Nseiken');
        
        $this->assertEquals('Cristian Garcia', $author->getFullname());
    }
}

PostTest.php

<?php

use App\Post;
use App\Author;
use App\Category;
use PHPUnit\Framework\TestCase;

class PostTest extends TestCase
{
    public function test_it_can_create_post_by_author()
    {
        $author = new Author('Cristian', 'Garcia', 'Nseiken');

        $category = new Category(['videojuegos', 'ocio']);

        $post = new Post('Mi gusto por Bioshock', 'Por su historia y jugabilidad', $author, $category);
        
        $author->setPost($post);
        
        $this->assertInstanceOf(Author::class, $post->getAuthor());
        $this->assertInstanceOf(Category::class, $post->getCategory());
        $this->assertEquals('Mi gusto por Bioshock', $post->getTitle());
        $this->assertEquals('Por su historia y jugabilidad', $post->getContent());
        $this->assertEquals(1, $author->getCountPosts());
    }
}