mustorze/mustafilter

用于 Laravel 的过滤器

1.5 2023-02-07 21:55 UTC

This package is auto-updated.

Last update: 2024-09-08 01:13:22 UTC


README

一个简单的 Laravel 过滤器管理工具,适用于 REST 和 GraphQL

先决条件

  • 要运行此项目,您必须具备 php >= 7.1laravel\framework >= 5.4.*webonyx/graphql-php ~0.10.0
  • 是的,它是为 Laravel 制作的

步骤 1

  • 在您的 composer.json 中添加以下依赖项:"mustorze/mustafilter": "1.0",然后运行 composer update

  • 或者直接运行 composer require mustorze/mustafilter

步骤 2

  • Mustorze\MustAFilter\Traits\Filterable 特性添加到您希望进行过滤的模型中。

步骤 3

  • Mustorze\MustAFilter\Contracts\Filter 抽象类扩展您的 Filter 类

  • 以下是一个针对 user 模型的示例过滤器

class UserFilter extends Mustorze\MustAFilter\Contracts\Filter
{
    /**
     * Declare here all the filters that can be used in the model
     */
    protected $filters = [
        'email'
    ];

    /**
    * If you're using GraphQL declare here the type and description of the filter
    * Available Types: 'string', 'boolean', 'integer', 'float', 'list-of-boolean', 'list-of-integer', 'list-of-float', 'list-of-string'
    */
    protected $filtersSpec = [
        'email' => [
            'type' => 'string', // You can specify any type available in GraphQL from the list above
            'description' => 'like filter by user email'
      ]
    ];

    /**
     * The filter will be applied to the constructor with the name declared in $filters
     *
     * @param $value
     * @return mixed
     */
    protected function email($value)
    {
        return $this->builder->where('email', 'LIKE', "%$value%");
    }
}
完成

如何使用

GraphQL

这是 GraphQL 中的默认查询

class UsersQuery extends Query
{
    /**
    * To makes things easy, i've create a const for the filter i will use in this query
    */
    const FILTER = UserFilter::class; // it's the same class that was created before

    /**
    * Query default configuration
    */
    protected $attributes = [
        'name' => 'Admin users query',
        'description' => 'The query pagination of users'
    ];

    /**
    * Query default type
    */
    public function type()
    {
        return GraphQL::paginate('user');
    }

    /**
     * Here is the first place we can modify, in this moment we need to use a `getFilterArgs` method to Get all the
     * filters we created in the Filter.
     * When you use `Filterable` trait, your model own the `getFilterArgs` automatic.
     * 1st param - The filter, you can create a infinites filters to use in your queries
     * 2nd param - The defaults args, pass in array the default args can you always do to the query
     */
    public function args()
    {
        return User::getFilterArgs($this::FILTER, [
            'page' => [
                'name' => 'page',
                'type' => Type::nonNull(Type::int()),
                'description' => 'The page'
            ],
            'limit' => [
                'name' => 'limit',
                'type' => Type::nonNull(Type::int()),
                'description' => 'The limit'
            ]
        ]);
    }

    /**
    * The default resolve
    */
    public function resolve($root, $args, SelectFields $fields, ResolveInfo $info)
    {
        $select = $fields->getSelect();
        $with = $fields->getRelations();

        /**
        * The second place to modify we found here, we need to pass filter scope to the builder, and then he will
        * validate and apply your filters in the query.
        * 1st param - The filter, you can create a infinites filters to use in your queries
        * 2rd param - There we pass the args of query, it`s simple, we need to get the passed values from query to
        * makes things working.
        */
        return User::select($select)
            ->with($with)
            ->filter($this::FILTER, $args) // The filter
            ->paginate($args['limit'], $select, 'page', $args['page']);
    }
}

如果您正确地完成了所有步骤,您可以轻松地通过在查询的 args 中传递您想要的过滤器来测试您的查询

现在我们知道了如何在 GraphQL 中使用它

REST

在 REST 中,我们通常会使用一些需要的参数来构建查询,并将查询的结果返回给请求者

示例

public function fetchAllUsers()
{
    return User::where('status', 1) // a default query settings
        ->get(); 
}

使用 Filter,您需要在构造函数中添加 Filter Scope。Filter Scope 会自动检测请求中的参数并将其应用到查询中

public function fetchAllUsers()
{
    return User::where('status', 1) // a default query settings
        ->filter(UserFilter::class) // do not need to pass the further parameters
        ->get(); 
}

现在,如果这个请求是 POST 或 GET,并且在请求中有一个 email 参数,那么 email 过滤器就会应用到构建器上,即 localhost/users/?email=example.com。我们创建的过滤器将对查询应用 where like,所有在 email 列中包含 example.com 的结果都将被返回