Search code examples
phplaravelinterfacelaravel-api

PHP/Laravel Interface for API class realization


I have an interface with search function:

interface Searcher
{
    public function search($text,$limit)
}

I have some realization based on API

class APISeach implements Searcher
{
   public function search($text,$limit)
   {
        $params = [
            'name' => $sName,
            'maxRows' => $iLimit,
        ];
        $response = Http::get('http://some_api_service/search', $params)->json();
   }
}

And I have some code which used this Search:

class MyController extends Controller
{
    private $seacher;
    
    public function __construct(Searcher $mySeacher)
    {
         $this->seacher = $mySeacher;
    }

    public function search($text,$limit=10)
    {
         $this->seacher->search($text,$limit)
    }
}

All looks fine (may be). But what if I need change API realization and it will be required another parameters. For example:

class AnotherAPISeach implements Searcher
{
   public function search($text,$language,$fuzzy,$limit)
   {
       $ApiObjectFromLib = new ApiObjectFromLib();
       $response = $ApiObjectFromLib->search($text,$language,$fuzzy,$limit)->json();
   }
}

So it's can not implement Searcher interface any more. Is it exists any way to use interfaces for API functions? All API can required various parameters and it's no good if I need change Interface or Controller code for each API.


Solution

  • You can use variadic arguments

    interface Searcher
    {
        public function search($text, $limit, ...$additional);
    }
    

    If that defeats the purpose of the interface is up to you to decide 😉 ​​​​​​​