Courses

Design Patterns in Laravel 11

After looking at Services, let's look at a Service example that gets us closer to the "classical" design patterns.

It's an example from our previous lesson. Remember TwitterService, auto-injected into the Controller?

app/Http/Controllers/PublishPostController.php:

use App\Models\Post;
use App\Services\TwitterService;
 
class PublishPostController
{
public function __invoke(Post $post, TwitterService $twitter)
{
// ... all other operations with `$post`
 
$tweetResponse = $twitter->tweet($tweetText);
 
if (! isset($tweetResponse['data']->id)) {
return;
}
 
$tweetUrl = "https://twitter.com/freekmurze/status/{$tweetResponse['data']->id}";
 
$post->onAfterTweet($tweetUrl);
 
$post->update(['tweet_sent' => true]);
}
}

TwitterService is a class built for interactions with Twitter via their external API. Look what may be inside that service:

app/Services/TwitterService.php:

namespace App\Services;
 
use Abraham\TwitterOAuth\TwitterOAuth;
 
class TwitterService
{
public function tweet(string $text): ?array
{
if (! app()->environment('production')) {
return null;
}
 
$twitter = new TwitterOAuth(
config('services.twitter.consumer_key'),
config('services.twitter.consumer_secret'),
config('services.twitter.access_token'),
config('services.twitter.access_token_secret')
);
 
return (array) $twitter->post('tweets', compact('text'));
}
}

In this case, it uses a third-party package for OAuth with Twitter. All good, right?

Now, two questions:

  1. What if that package gets abandoned?
  2. What if Twitter's official API changes again? (hi Elon)

Then, this Service class would probably need to find and use another package or use the Twitter API directly to post a tweet.

So then, you have a choice...

This lesson is only for Premium Members.
Want to access all lessons of this course?

You also get:

  • 63 courses (1128 lessons, 42 h 01 min total)
  • Premium tutorials
  • Access to repositories
  • Private Discord