0

I am currently developing the backend for a news application, which fetches news from various aggregators (e.g. Feedly). I thought this qualified as a good use case for the adapter design pattern, so here’s what I did:

I created a configuration file that houses all the relevant information about each aggregator, including its adapter

return [
    'news-api' => [
        'url' => 'https://newsapi.org/v2/',
        'api-key' => env('NEWS_API_KEY'),
        'name' => 'News API',
        'adapter' => 'NewsApiAdapter'
    ],
    'feedly' => [
        'url' => 'https://cloud.feedly.com/v3/',
        'api-key' => env('FEEDLY_API_KEY'),
        'name' => 'Feedly',
        'adapter' => 'FeedlyApiAdapter'
    ],
];

I created an interface that each adapter must implement

interface NewsInterface
{
    public function fetchNews() : array;
}

And then I put it all together and used it like so

public function handle()
{
    foreach ($this->config as $config) {
        $adapterClassName = 'App\Adapters\\' . $config['adapter'];
        $adapterClass = new 
        $adapterClassName($this->client);
        $adapterClass->fetchNews();
    }
}

Now, my questions are as follows:

  1. Is this a good use case for the adapter design pattern?
  2. Does my current implementation effectively employ the adapter design pattern?
  3. Is there another design paradigm that is better suited to solve this problem?
1

If you're just implementing your interface exactly how you need it for each implementation, then I wouldn't exactly consider your solution the Adapter Pattern, rather just simple Polymorphism.

In terms of suggestions for better solutions, a couple things:

  1. Passing the class name as a string and then concating it to the package and using that variable to instantiate the class seems very "hacky" to me. If you want to keep that pattern, I would suggest passing \Your\Package\YourNewsApiFetcher::class in your config data.
  2. The Observer Pattern seems to me like the natural solution to solve this problem. It essentially has a list of "observers" listening to "events" which can be "published" / "subscribed to". In your case I would have your common Api fetchers publish an event whenever they pull the most up to date news, and your handler (or "observer") would subscribe to those events and handle them however you need to.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.