Home » Php » laravel – how to use polymorphism with static methods PHP

laravel – how to use polymorphism with static methods PHP

Posted by: admin February 25, 2020 Leave a comment

Questions:

I am working with php and the Laravel framework, my problem is the following: I have a class that helps me apply filters to a query to my database. Basically the class receives the filters to apply and searches for them, since these are in different classes, this is an example of what my class looks like:

<?php

namespace App\Filters\ProductSearch;

use App\Product;
use Illuminate\Http\Request;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Str;

class ProductSearch
{
    public static function apply(Request $filters)
    {
        $query = static::applyDecoratorsFromRequest($filters, (new Product)->newQuery());
        return static::getResults($query, $filters);
    }

    private static function applyDecoratorsFromRequest(Request $request, Builder $query)
    {
        foreach ($request->input('filters') as $key => $data) {

            $decorator = static::createFilterDecorator($data['field']);

            if (static::isValidDecorator($decorator)) {
                $query = $decorator::apply($query, $data);
            }
        }
        return $query;
    }

    private static function createFilterDecorator($name)
    {
        return __NAMESPACE__ . '\Filters\' . Str::studly($name);
    }

    private static function isValidDecorator($decorator)
    {
        return class_exists($decorator);
    }

    private static function getResults(Builder $query, $request)
    {
        return $query->orderBy('id', 'DESC')->paginate($request->take);
    }
}

well and so I use this class in my controller:

<?php

namespace App\Http\Controllers;

use App\Product;
use Illuminate\Http\Request;
use App\Filters\ProductSearch\ProductSearch;

class ProductController extends Controller
{
    public function index(Request $request)
    {
       return ProductSearch::apply($request);
    }
}

So, I need to use the logic of my ProductSearch class in another class but only by changing the behavior of the getResults() method, so I had thought about creating a base class and overloading this method, I think that applies to the concept of Polymorphism, since I still have doubts about these concepts, I don’t know if this is the right thing for static methods. or so how should I do it? Any guide or help will be very grateful. THANKS

How to&Answers: