Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //trigger event
- // Event
- class UserEarnedExperience
- {
- public $user;
- public function __construct($user)
- {
- $this->user = $user;
- }
- }
- // Listener
- class AwardAchivements
- {
- public function handle(UserEarnedExperience $event)
- {
- $achivementIdsToAwward = app('achievements')->filter(function ($achievement) use ($event) {
- return $achievement->qualified($event->user);
- })->map(function ($achievement) {
- return $achievement->modelKey();
- });
- $event->user->achievements()->sync($achivementIdsToAwward);
- }
- }
- class FirstThousandPoints extends AchievementType
- {
- public $name = 'First Thousand Points';
- public $description = 'Achieved by getting to 1000 points';
- public $icon = 'thousand-points.svg';
- public $level = 'beginer';
- public function qualified($user)
- {
- return $user->points >= 1000;
- }
- }
- class StartYourEngines extends AchievementType
- {
- public $name = 'Start your engines';
- public $description = 'Achieved by completing at least one lesson';
- public $icon = 'start-your-engines.svg';
- public $level = 'beginer';
- public function qualified($user)
- {
- return $user->completions()->count() >= 1;
- }
- }
- abstract class AchievementType
- {
- // we might take a different approach to populate the database
- // Achievement is the Model with many2many relationship with User
- public function __construct()
- {
- $this->model = Achievement::firstOrCreate([
- 'name' => $this->name,
- 'description' => $this->description,
- 'icon' => $this->icon,
- 'level' => $this->level
- ]);
- }
- public function modelKey()
- {
- return $this->model->getKey();
- }
- }
- class AchievementServiceProvider extends ServiceProvider
- {
- protected $achievements = [
- FirstThousandPointsAchievement::class,
- StartYourEngines::class
- ];
- public function register()
- {
- $this->app->singleton('achievement', function () {
- // caching because instead of hitting database every time on every user we hit only once
- // now when we hit this it looks up for achievement classes in cache
- // dont forget to clear cache when creating new achievement
- return cache()->rememberForever('achievements', function () {
- return collect($this->achievements)->map(function ($achievement) {
- return new $achievement;
- });
- });
- });
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement