Skip to content

Implement new Post Collection(s) API #2308

@acobster

Description

@acobster

Per discussion here: #2073 (comment)

I believe that the best approach here is to define a PostCollectionInterface, and return a different concrete instance depending on whether we've been passed an array or a WP_Query. Here's the API I propose, based on what's currently in PostQuery, PostCollection, and QueryIterator:

interface PostCollectionInterface extends Traversable, Countable, ArrayAccess {
  public function pagination( array $options = [] );
}

// NOTE: was called PostQueryIterator in previous draft, but I think this is less confusing.
class PostQuery implements PostCollectionInterface {
  public function pagination( array $option = [] ) {
    return new Pagination($options, $this->_query);
  }
  /* all the same traversal/counting methods currently in QueryInterface, plus ArrayAccess methods... */
}

class PostArrayObject extends ArrayObject implements PostCollectionInterface {
  public function pagination( array $options = [] ) {
    return null;
  }
}

A couple things to note:

  • I chose to extend those interfaces specifically because they are close to the lowest common denominator of ArrayObject (which PostCollection extends) and Iterator/Countable (which QueryIterator implements). Also because ArrayAccess is nice, and easy to implement.
  • PostArrayObject already implements Traversable etc. by virtue of extending ArrayObject.
  • A Factory can decide which class to instantiate based on whatever was passed to ::from().

We should document PostCollectionInterface and the classes that implement it. Maybe a future version of Timber can expose a filter for overriding the concrete instance of PostCollectionInterface returned from Timber::get_posts() (i.e. a Class Map filter), but we don't need that right now.

Metadata

Metadata

Assignees

No one assigned

    Labels

    2.0wipWork in Progress

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions