h2onock

h2onock

Member Since 4 Months Ago

Experience Points 50
Experience Level 1

4,950 experience to go until the next level!

In case you were wondering, you earn Laracasts experience when you:

  • Complete a lesson — 100pts
  • Create a forum thread — 50pts
  • Reply to a thread — 10pts
  • Leave a reply that is liked — 50pts
  • Receive a "Best Reply" award — 500pts
Lessons Completed 0
Lessons
Completed
Best Reply Awards 0
Best Reply
Awards
  • start-engines Created with Sketch.

    Start Your Engines

    Earned once you have completed your first Laracasts lesson.

  • first-thousand Created with Sketch.

    First Thousand

    Earned once you have earned your first 1000 experience points.

  • 1-year Created with Sketch.

    One Year Member

    Earned when you have been with Laracasts for 1 year.

  • 2-years Created with Sketch.

    Two Year Member

    Earned when you have been with Laracasts for 2 years.

  • 3-years Created with Sketch.

    Three Year Member

    Earned when you have been with Laracasts for 3 years.

  • 4-years Created with Sketch.

    Four Year Member

    Earned when you have been with Laracasts for 4 years.

  • 5-years Created with Sketch.

    Five Year Member

    Earned when you have been with Laracasts for 5 years.

  • school-session Created with Sketch.

    School In Session

    Earned when at least one Laracasts series has been fully completed.

  • welcome-newcomer Created with Sketch.

    Welcome To The Community

    Earned after your first post on the Laracasts forum.

  • full-time-student Created with Sketch.

    Full Time Learner

    Earned once 100 Laracasts lessons have been completed.

  • pay-it-forward Created with Sketch.

    Pay It Forward

    Earned once you receive your first "Best Reply" award on the Laracasts forum.

  • subscriber-token Created with Sketch.

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • lifer-token Created with Sketch.

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • lara-evanghelist Created with Sketch.

    Laracasts Evangelist

    Earned if you share a link to Laracasts on social media. Please email [email protected] with your username and post URL to be awarded this badge.

  • chatty-cathy Created with Sketch.

    Chatty Cathy

    Earned once you have achieved 500 forum replies.

  • lara-veteran Created with Sketch.

    Laracasts Veteran

    Earned once your experience points passes 100,000.

  • 10k-strong Created with Sketch.

    Ten Thousand Strong

    Earned once your experience points hits 10,000.

  • lara-master Created with Sketch.

    Laracasts Master

    Earned once 1000 Laracasts lessons have been completed.

  • laracasts-tutor Created with Sketch.

    Laracasts Tutor

    Earned once your "Best Reply" award count is 100 or more.

  • laracasts-sensei Created with Sketch.

    Laracasts Sensei

    Earned once your experience points passes 1 million.

  • top-50 Created with Sketch.

    Top 50

    Earned once your experience points ranks in the top 50 of all Laracasts users.

18 May
4 months ago

h2onock started a new conversation Laravel - Grouping Service Providers?

Hi all, I'm trying to accomplish something with Laravel 5.8 that I've not needed to do before, wanted your advice.

I've changed exactly what I'm trying to do to something very similar so feel free to steal this idea if you want, but the premise is the same for what I'm really trying to do.

The user can view news from several different services, say bbc and sky.

I have a BBCNewsProvider and an SkyNewsProvider set up and both work fine.

The default is BBC but the user can change the setting to Sky if they wish.

I have a NewsController that looks something like this:

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Pagination\LengthAwarePaginator as Paginator;
use Illuminate\Support\Facades\Auth;

use App\Providers\NewsSkyProvider;
use App\Providers\NewsBBCProvider;

class NewsController extends Controller
{
    protected $news_pvdr;

    public function __construct(NewsBBCProvider $pvdr_bbc, 
                             NewsSkyProvider $pvdr_sky)
    {
        $this->pvdr_bbc = $pvdr_bbc;
        $this->pvdr_sky = $pvdr_sky;
    }

    private function get_results(Request $req)
    {
        $page = (int)$req->query('page') ?: 1;

        $r = $this->news_pvdr->get_results($req->query('q'), $page, $per_page);

        $max = $r->results_total_cnt > \Config::get('news.pagination_max_num') ?
                        \Config::get('news.pagination_max_num') :
                                $r->results_total_cnt;

        $paginator = new Paginator($r->results, $max, $per_page, $page,
            [
                'path'  => $req->url(),
                'query' => $req->query(),
            ]
        );

        $r->results = $paginator;

        return $r;
    }

    private function set_pvdr()
    {
        $pvdrs = [
            'sky' => $this->pvdr_sky,
            'bbc' => $this->pvdr_bbc,
        ];

        $default = \Config::get('news.default_news_provider');
        $user_chosen = \Setting::get('news_pvdr');

        if (!in_array($default, $pvdrs))
            \Log::emergency('The default news provider is invalid');

        /* which news provider should we use? */
        /* get provider model */
        $default_pvdr = $pvdrs[$default];
        if ($user_chosen && in_array($desd, $pvdrs))
            $desd = $pvdrs[$desd];
        else
            $desd = $default_pvdr;

        /* if the chosen provider not enabled, fall back to default */
        if ($desd->enabled)
            $this->news_pvdr = $desd;
        else if ($default_pvdr->enabled)
            $this->news_pvdr = $default_pvdr;
        else
            \Log::emergency('No news providers are enabled.');
    }

    public function perform(Request $req)
    {
        $this->set_pvdr();

        $r = $this->get_results($req);

        return view('news', [ 'response' => $r ]);
    }
}

This works fine with News Providers that look like this: 

namespace App\Providers;

use \App\News;
use \App\NewsResults;

use Illuminate\Support\Facades\DB;
use Illuminate\Support\ServiceProvider;

class NewsBBCProvider extends ServiceProvider
{
    public $name = 'bbc';
    public $enabled = 1;

    /**
    * Register services.
    *
    * @return void
    */
    public function register()
    {
        $this->app->bind('App\Providers\NewsBBCProvider', function($app) {
            return new NewsBBCProvider($app);
        });
    }

    private function parse_results(?array $response):NewsResults
    {
        $sr = new NewsResults();
        $sr->provider = 'BBC';
        if (!$response)
            return $sr;

        $r = $response['response'];

        /* fix encoding of bbc response */
        foreach ($r['results'] as $k => $v) {
            $r['results'][$k]['title'] = html_entity_decode($v['title'], ENT_QUOTES, 'UTF-8');
            $r['results'][$k]['desc'] = html_entity_decode($v['desc'], ENT_QUOTES, 'UTF-8');
        }

        $sr->query = $r['head']['query'];
        $sr->results = $r['results'];
        $sr->results_start = (int)$r['head']['start'];
        $sr->results_end = (int)$r['head']['start'] + (int)$r['head']['return'] - 1;
        $sr->results_total_cnt = (int)$r['head']['results'];

        return $sr;
    }

    public function get_results(string $q, $page, $per_page)
    {
        $url = /* the url */
        $curl_opts = [
            CURLOPT_URL       => $url,
            CURLOPT_USERAGENT => 'TODO',
            CURLOPT_TIMEOUT   => 15,
            CURLOPT_RETURNTRANSFER => 1,
        ];

        $ch = curl_init();
        curl_setopt_array($ch, $curl_opts);

        $response = curl_exec($ch);

        $errors = curl_error($ch);
        $http_response_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);

        curl_close($ch);

        $r = $response ? json_decode($response, true) : null;

        return $this->parse_results($r);
    }
}

The Providers are registered in the normal place ('app.providers').

If I decided to add more providers then I could by copying an existing provider, changing a few bits and then updating the NewsController __construct function accordingly.

However, I also want a settings page that allows the user to choose which should be default. I don't really want to have to update the __construct function in that controller every time I add/remove a service provider, I only really want to add/remove them in one place. I might need to show/use all NewsProviders elsewhere in the app too so being able to grab them all at the same time would be great.

How would I get around this? At first I wondered if I could sort of 'group' all News Providers somehow and inject the group into the NewsController, SettingsController etc... If I then edited the group then voila, I'd get what I want. However I've searched the docs and can't find anything. The answer is probably quite simple for the more seasoned Laravel pro's, at least I hope so!

Thanks all.