Rethinking with events -
6 min read
fairly easy
A real-life example of how an event-driven system can improve code quality
By continuing your visit to this site, you accept the use of cookies. Read more

« back — written by Brent on July 14, 2021

Rethinking with events

I'm working on a new feature for our Spatie website: I'm adding a lightweight form of gamification for our ±10.000 users.

Here's how it works: every time a user watches one of our course videos, every time they complete a video series or a pull request gets merged on GitHub, they'll receive experience points. On top of that, there are also some achievements to reward users for their efforts. For example there's a "10 pull requests" achievement, as well as a "100 XP" achievement and a few others.

Getting an achievement will reward the user with a digital badge, and in some cases they'll get some kind of certificate as well.

As you can see, it's a small, contained system, with well defined boundaries. And I'd like to discuss one aspect of it with you today.

Let's zoom in on one of the possible flows: the pull request reward system. There are a few steps to it:

Register a user's pull request

Award some XP for it

Check whether this pull request is eligible for an achievement

If that's the case, unlock a badge and notify the user

Writing this flow down in bullets makes it feel like the pull request reward system is a linear process. In fact, we could write it like so:

class RegisterPullRequest { public function __invoke ( PullRequestData $data) : void { $pullRequest = PullRequest :: create (...$data); $user = $pullRequest-> user ; $user-> award ( 10 ); $pullRequestCount = count ($user-> pullRequests ); if ( in_array ($pullRequestCount, [ 10 , 50 , 100 ])) { $achievement = new PullRequestAchievement ($pullRequestCount); $user-> unlock ($achievement); $user-> notify ( new AchievmentNotification ($achievement)); } } }

You might want to refactor this code to separate methods or to use injected actions or service classes if you prefer that style of programming; but I wanted to keep this example concise, to easily…
Noticed A Tpyo, You Can Submit A
Read full article