1final class VacancyController
2{
3 public function publish(Request $request, Vacancy $vacancy): RedirectResponse
4 {
5 $this->authorize('publish', $vacancy);
6
7 $vacancy->update(['status' => 'published', 'published_at' => now()]);
8 $this->telegram->post($vacancy);
9 $this->search->index($vacancy);
10
11 Log::info('vacancy.published', ['id' => $vacancy->id, 'by' => $request->user()->id]);
12
13 return back()->with('status', 'Вакансію опубліковано');
14 }
15}
1<?php
2
31final readonly class PublishVacancy
4{
5 public function __construct(public int $vacancyId, public string $by) {}
6}
7
82final class PublishVacancyHandler
9{
10 /** @param array<int, string> $vacancies */
11 public function __construct(private array $vacancies) {}
12
13 public function __invoke(PublishVacancy $command): void
14 {
15 echo " опубліковано «{$this->vacancies[$command->vacancyId]}», пост у Telegram\n";
16 }
17}
18
19final class CommandBus
20{
21 /** @var list<object> */
22 private array $queue = [];
23
24 /** @var list<string> */
25 public array $log = [];
26
27 /** @param array<class-string, callable> $handlers */
28 public function __construct(private array $handlers) {}
29
303 public function dispatch(object $command): void
31 {
32 $this->log[] = $command::class . ' від ' . $command->by;
33 ($this->handlers[$command::class])($command);
34 }
35
364 public function later(object $command): void
37 {
38 $this->queue[] = $command;
39 echo ' у черзі: ', count($this->queue), "\n";
40 }
41
42 public function work(): void
43 {
44 while ($command = array_shift($this->queue)) {
45 $this->dispatch($command);
46 }
47 }
48}
49
50$bus = new CommandBus([
51 PublishVacancy::class => new PublishVacancyHandler([7 => 'Senior Laravel Developer', 8 => 'PHP Team Lead']),
52]);
53
54echo "Кнопка на сайті:\n";
55$bus->dispatch(new PublishVacancy(7, by: 'olena@company.ua'));
56
57echo "Публікація за розкладом на 9:00:\n";
58$bus->later(new PublishVacancy(8, by: 'scheduler'));
59echo "О 9:00 воркер бере чергу:\n";
60$bus->work();
61
62echo "Журнал:\n ", implode("\n ", $bus->log), "\n";