jjgrainger/query

WordPress 查询构建器

v0.2.0 2022-06-26 14:47 UTC

This package is auto-updated.

Last update: 2024-09-07 15:07:48 UTC


README

用于创建 WordPress 查询的流畅接口

tests codecov Total Downloads Latest Stable Version License

需求

安装

$ composer require jjgrainger/query

用法

Query 类为在 WordPress 中创建 WP_Query 提供了一个流畅的接口。

use Query\Query;

// Create a new WP_Query for the latest 3 products.
$results = Query::post_type( 'product' )->posts_per_page( 3 )->get();

// The above is the same as...
$args = [
    'post_type'      => 'product',
    'posts_per_page' => 3,
];

$results = new \WP_Query( $args );

创建自定义查询类

可以通过扩展 Query 类来创建自定义查询类。自定义查询类可以封装默认参数,然后可以通过查询方法进行扩展。

例如,可以创建一个 FeaturedPostsQuery 来返回具有 'featured' 分类术语的文章。默认查询参数在接收 Builder 实例的 setup() 方法中定义。

use Query\Query;
use Query\Builder;

class FeaturedPostsQuery extends Query
{
    /**
     * Setup the initial query.
     *
     * @param  Builder $builder
     *
     * @return Builder
     */
    public function setup( Builder $builder ): Builder
    {
        // Setup a tax_query for posts with the 'featured' term.
        $tax_query = [
            [
                'taxonomy' => 'featured',
                'fields'   => 'slugs',
                'terms'    => [ 'featured' ],
            ],
        ];

        return $builder->where( 'tax_query', $tax_query );
    }
}

一旦创建了查询类,就可以在项目中的各种方式中使用它。

use FeaturedPostsQuery as Featured;

// Returns a WP_Query object for posts with the featured term.
$results = Featured::get();

// Returns a WP_Query object for the latest 3 products with the featured term.
$results = Featured::type( 'products' )->limit( 3 )->get();

// Queries can be instantiated with an array of additional query arguments.
$args = [
    'post_type' => 'products',
];

// Create a query object.
$query = new Featured( $args );

// Modify the query and get the WP_Query object.
$results = $query->limit( 3 )->get();

自定义作用域

可以使用静态 addScope 方法将自定义作用域添加到全局 Query 中。添加作用域最简单的方法之一是使用闭包。

// Create a new scope with a closure.
Query::addScope( 'events', function( Builder $builder ) {
    return $builder->where( 'post_type', 'event' );
} );

// Call the scope when needed.
$results = Query::events()->limit( 3 );

自定义作用域类

可以将自定义作用域类添加到全局 Query。自定义作用域类需要实现 Scope 接口并包含所需的 apply 方法。apply 方法应接受查询 Builder 作为第一个参数以及通过作用域传递的任何可选参数。一旦添加到 Query 类中,作用域将通过类名(第一个字母小写)可用。

// Create a custom scope class.
use Query\Scope;
use Query\Builder;

class PostID implements Scope {
    public function apply( Builder $builder, $id = null ) {
        return $builder->where( 'p', $id );
    }
}

// Add the scope to the Query.
Query::addScope( new PostID );

// Use the scope in the Query.
$results = Query::postID( 123 )->get();

注意

作者

Joe Grainger