如何创建一个将返回数组或单个项目的类?

时间:2018-12-11 15:50:53

标签: php class

我正在编写一个我希望以后可以调用的类,让它返回一个值数组,但它只返回一个值。

我希望能够像这样使用我的课程。如果我指定一个用户ID新Blog([10]),则它不应返回一个数组,而仅返回一个实例。如果我指定了多个用户ID,则它应该返回一组项目。

我正在尝试创建类似于Laravel的工作方式,在这里您可以说$ posts = Posts :: all();或$ posts = Post :: where('id',10)-> first();在第一个中,它将返回所有帖子的数组,在第二个中,它将仅返回一个帖子。

用法示例:

// 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
}

我的课程

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';
            }
        }
    }
}

1 个答案:

答案 0 :(得分:0)

我了解您为什么要这样做,并且由于您提出了另一种要求,所以就在这里。一种方法是编写static method来检索您的博客:

class Blog {
  public static function fetchBlogsByIds() {
    // [...]
  }
  // [...]
} 

然后您以这种方式调用该方法:

$blogs = Blog::fetchBlogsByIds(ids) {
  $blogs = array();
  foreach($ids as $id) {
    $blogs[] = new Blog($id); // appending a new Blog entry
  }
  return $blogs;
}

您还可以编写一个名为 collection 的类,例如 BlogCollection ,并为其提供依赖于ID数组的构造函数。

class BlogCollection {

  // Builds the collection by the ids
  function __construct(ids) {
    // [...] similar implementation as fetchBlogsByIds() above
  }

  // [...]
}

然后,您可以通过以下方式检索博客:

blogs = new BlogCollection([10, 11]);

如果您想在自定义集合中使用foreach,则可以使其实现TraversableIterator