Search code examples
phpcakephp

CakePHP philosophical question


So i have a lot of different model types. Comments, posts, reviews, etc. And I want to join them into one integrated feed. Is there a CakePHP style of merging all this data for display, ordered by timestamp?

There are a lot of messy ways to do this but I wonder if there is some standard way which I am missing. Thanks!


Solution

  • Since the items are from different tables, it's difficult to retrieve them sorted together from the database in any case. Depending on how well organized your data is though, something as non-messy as this should do:

    $posts = $this->Post->find(...);
    $reviews = $this->Review->find(...);
    $comments = $this->Comment->find(...);
    
    $feed = array_merge($posts, $reviews, $comments);
    usort($feed, function ($a, $b) {
        $a = current($a);
        $b = current($b);
        return strtotime($a['created']) - strtotime($b['created']);
    });