How to create a class that will return an array or single item?

Posted 4 months ago by MartinZeltin

I am writing a class that I would like to be able to call later and have it return an array of values but it is returning only one.

I would like to be able to use my class like this. If I specify one user id new Blog([10]) then it shouldn't return an array but only one instance. If I specify more than one user id then it should return an array of items.

I am trying to create something similar to how Laravel works where you can say $posts = Posts::all(); or $posts = Post::where('id', 10)->first(); and in the first one it would return an array of all posts and in second it would return only one.

Example usage:

    // Get one user's blog
    $blog = new Blog([10]); // specify user ids
    
    echo $blog->user->name;      // Jane Smith
    echo $blog->posts->title;    // How to draw
    echo $blog->posts->body;     // In this post, I will teach you...
    echo $blog->posts->created;  // 2018-12-01
    echo $blog->theme;           // light/dark/other
    echo $blog->is_awesome;      // no
    
    // Get blogs for users - 10, 20, 30
    $blogs = new Blog([10, 20, 30]); // specify user ids
    
    foreach ($blogs as $blog) {
        echo $blog->user->name;     // John Doe
        echo $blog->posts->title;   // 10 ways to live
        echo $blog->posts->body;    // Hello, in this post I will..
        echo $blog->posts->created; // 2018-12-31
        echo $blog->theme;          // light/dark/other
        echo $blog->is_awesome;     // yes
    }

My class

    Class Blog
    {
        public $users;
        public $posts;
        public $comments;
        public $theme;
        public $is_awesome;
    
        function __construct($users)
        {
            $this->users     = new stdClass();
            $this->users->id = $users; // array of ids
    
            foreach ($this->users as $user) {
                $this->user->name = self::getUsername($user->id)  // John
                $this->posts      = self::getPosts($user->id);    // array of posts
                $this->comments   = self::getComments($user->id); // array of comments
                $this->theme      = self::getTheme($user->id);    // light/dark/other
    
                if ($this->theme == 'dark') {
                    $this->is_awesome = 'yes';
                } else {
                    $this->is_awesome = 'no';
                }
            }
        }
    }

Please sign in or create an account to participate in this conversation.

Reply to

Use Markdown with GitHub-flavored code blocks.