-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtutorial-building-todo-app.html
More file actions
1560 lines (1349 loc) · 64.7 KB
/
tutorial-building-todo-app.html
File metadata and controls
1560 lines (1349 loc) · 64.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html lang="en" class="scroll-smooth">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Forge Kernel - Tutorial</title>
<script src="https://cdn.tailwindcss.com"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/components/prism-core.min.js"></script>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/plugins/autoloader/prism-autoloader.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/themes/prism-tomorrow.min.css" rel="stylesheet">
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
<link rel="stylesheet" href="assets/css/docs.css">
</head>
<body class="bg-gray-50 text-gray-900">
<!-- Navigation -->
<nav class="bg-white shadow-sm border-b">
<div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
<div class="flex justify-between h-16">
<div class="flex items-center">
<div class="flex-shrink-0">
<h1 class="text-xl font-bold text-gray-900">
Forge Kernel
</h1>
</div>
<div class="hidden sm:ml-6 sm:flex sm:space-x-8">
<a href="index.html"
class="text-gray-900 inline-flex items-center px-1 pt-1 text-sm font-medium hover:text-blue-600">
Home
</a>
<a href="getting-started.html"
class="text-gray-900 inline-flex items-center px-1 pt-1 text-sm font-medium hover:text-blue-600">
Getting Started
</a>
<a href="core-concepts.html"
class="text-gray-900 inline-flex items-center px-1 pt-1 text-sm font-medium hover:text-blue-600">
Core Concepts
</a>
<a href="modules.html"
class="text-gray-900 inline-flex items-center px-1 pt-1 text-sm font-medium hover:text-blue-600">
Capabilities
</a>
<a href="api-reference.html"
class="text-gray-900 inline-flex items-center px-1 pt-1 text-sm font-medium hover:text-blue-600">
API Reference
</a>
<a href="tutorial.html"
class="text-blue-600 inline-flex items-center px-1 pt-1 text-sm font-medium border-b-2 border-blue-600">
Tutorials
</a>
</div>
</div>
<!-- Mobile menu button -->
<div class="flex items-center sm:hidden">
<button id="mobile-menu-button" class="text-gray-700 hover:text-blue-600 p-2">
<i class="fas fa-bars text-xl"></i>
</button>
</div>
</div>
</div>
<!-- Mobile menu -->
<div id="mobile-menu" class="sm:hidden hidden bg-white border-t border-gray-200">
<div class="px-2 pt-2 pb-3 space-y-1">
<a href="index.html" class="block px-3 py-2 text-gray-900 hover:text-blue-600">Home</a>
<a href="getting-started.html" class="block px-3 py-2 text-gray-900 hover:text-blue-600">Getting
Started</a>
<a href="core-concepts.html" class="block px-3 py-2 text-gray-900 hover:text-blue-600">Core Concepts</a>
<a href="modules.html" class="block px-3 py-2 text-gray-900 hover:text-blue-600">Capabilities</a>
<a href="api-reference.html" class="block px-3 py-2 text-gray-900 hover:text-blue-600">API Reference</a>
<a href="tutorial.html" class="block px-3 py-2 text-blue-600 font-medium">Tutorials</a>
</div>
</div>
</nav>
<!-- Main Content -->
<div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
<!-- Breadcrumb Navigation -->
<nav class="mb-6" aria-label="Breadcrumb">
<ol class="flex items-center space-x-2 text-sm text-gray-500">
<li><a href="index.html" class="hover:text-blue-600">Home</a></li>
<li><i class="fas fa-chevron-right text-xs"></i></li>
<li><a href="tutorial.html" class="hover:text-blue-600">Tutorials</a></li>
<li><i class="fas fa-chevron-right text-xs"></i></li>
<li class="text-gray-900 font-medium">Building a Todo App</li>
</ol>
</nav>
<div class="flex flex-col lg:flex-row gap-8">
<!-- Sidebar Navigation -->
<div id="sidebar-nav" class="lg:w-1/4">
<div class="bg-white rounded-lg shadow-sm p-6 sticky top-8 max-h-[calc(100vh-4rem)] overflow-y-auto">
<h3 class="text-lg font-semibold text-gray-900 mb-4">Tutorial</h3>
<nav class="space-y-2">
<a href="#introduction"
class="nav-link block px-3 py-2 text-sm text-gray-700 rounded-md hover:text-blue-600">Introduction</a>
<a href="#project-setup"
class="nav-link block px-3 py-2 text-sm text-gray-700 rounded-md hover:text-blue-600">Project
Setup</a>
<a href="#database-models"
class="nav-link block px-3 py-2 text-sm text-gray-700 rounded-md hover:text-blue-600">Database
& Models</a>
<a href="#authentication"
class="nav-link block px-3 py-2 text-sm text-gray-700 rounded-md hover:text-blue-600">Authentication</a>
<a href="#controllers-routes"
class="nav-link block px-3 py-2 text-sm text-gray-700 rounded-md hover:text-blue-600">Controllers
& Routes</a>
<a href="#views-layouts"
class="nav-link block px-3 py-2 text-sm text-gray-700 rounded-md hover:text-blue-600">Views
& Layouts</a>
<a href="#forgewire"
class="nav-link block px-3 py-2 text-sm text-gray-700 rounded-md hover:text-blue-600">ForgeWire
Components</a>
<a href="#events"
class="nav-link block px-3 py-2 text-sm text-gray-700 rounded-md hover:text-blue-600">Events</a>
<a href="#testing"
class="nav-link block px-3 py-2 text-sm text-gray-700 rounded-md hover:text-blue-600">Testing</a>
<a href="#putting-together"
class="nav-link block px-3 py-2 text-sm text-gray-700 rounded-md hover:text-blue-600">Putting
It All Together</a>
</nav>
</div>
</div>
<!-- Main Content -->
<div class="lg:w-3/4">
<div class="bg-white rounded-lg shadow-sm p-8">
<h1 class="text-4xl font-bold text-gray-900 mb-6">Building a Todo Application</h1>
<p class="text-xl text-gray-600 mb-8">
A step-by-step tutorial demonstrating how to combine multiple Forge Kernel features and modules
to build a complete application.
</p>
<!-- Introduction -->
<section id="introduction" class="section-anchor mb-12">
<h2 class="text-2xl font-bold text-gray-900 mb-4">Introduction</h2>
<p class="text-gray-600 mb-6">
In this tutorial, we'll build a todo application that demonstrates how to use multiple Forge
Kernel modules together. This "glorified todo" app will showcase authentication, database
operations, interactive components, events, and testing.
</p>
<h3 class="text-lg font-semibold mb-3">What We're Building</h3>
<p class="text-gray-600 mb-4">
A todo application with the following features:
</p>
<ul class="list-disc list-inside space-y-2 text-gray-600 mb-6">
<li>User authentication (registration and login)</li>
<li>CRUD operations for todos (Create, Read, Update, Delete)</li>
<li>Interactive todo list with real-time updates (ForgeWire)</li>
<li>Background event processing for notifications</li>
<li>Comprehensive test coverage</li>
<li>User-specific todos (each user sees only their todos)</li>
</ul>
<h3 class="text-lg font-semibold mb-3">Modules We'll Use</h3>
<ul class="list-disc list-inside space-y-2 text-gray-600 mb-6">
<li><strong>ForgeAuth:</strong> User authentication and session management</li>
<li><strong>ForgeDatabaseSql:</strong> Database migrations and schema management</li>
<li><strong>ForgeSqlOrm:</strong> Object-Relational Mapping for models</li>
<li><strong>ForgeWire:</strong> Interactive components with real-time updates</li>
<li><strong>ForgeEvents:</strong> Event-driven architecture and background processing</li>
<li><strong>ForgeTesting:</strong> Comprehensive testing framework</li>
</ul>
<h3 class="text-lg font-semibold mb-3">Prerequisites</h3>
<ul class="list-disc list-inside space-y-2 text-gray-600 mb-6">
<li>PHP 8.3 or higher</li>
<li>Forge Kernel installed and configured</li>
<li>Basic understanding of PHP and object-oriented programming</li>
<li>Familiarity with MVC architecture (helpful but not required)</li>
</ul>
<div class="bg-blue-50 border-l-4 border-blue-400 p-4 mb-6">
<p class="text-sm text-blue-700">
<strong>Note:</strong> This tutorial assumes you have Forge Kernel installed. If not,
please refer to the <a href="getting-started.html" class="underline">Getting Started</a>
guide first.
</p>
</div>
</section>
<!-- Project Setup -->
<section id="project-setup" class="section-anchor mb-12">
<h2 class="text-2xl font-bold text-gray-900 mb-4">Project Setup</h2>
<p class="text-gray-600 mb-6">
Let's start by setting up our project and installing the required modules.
</p>
<h3 class="text-lg font-semibold mb-3">Installing Required Modules</h3>
<p class="text-gray-600 mb-4">
We'll need several modules for our todo application. Install them using ForgePackageManager:
</p>
<pre class="bg-gray-100 p-4 rounded mb-4"><code class="language-bash"># Install authentication module
php forge.php module:package-install --module=forge-auth
# Install database SQL module
php forge.php module:package-install --module=forge-database-sql
# Install SQL ORM module
php forge.php module:package-install --module=forge-sql-orm
# Install ForgeWire for interactive components
php forge.php module:package-install --module=forge-wire
# Install ForgeEvents for background processing
php forge.php module:package-install --module=forge-events
# Install ForgeTesting for testing
php forge.php module:package-install --module=forge-testing</code></pre>
<h3 class="text-lg font-semibold mb-3 mt-6">Configuring Middleware</h3>
<p class="text-gray-600 mb-4">
After installing ForgeWire, you must register its middleware in
<code>config/middlewares.php</code> to enable the reactive engine:
</p>
<pre class="bg-gray-100 p-4 rounded mb-4"><code class="language-php"><?php
return [
'global' => [],
'web' => [
\App\Modules\ForgeWire\Middlewares\ForgeWireMiddleware::class,
],
'api' => []
];</code></pre>
<h3 class="text-lg font-semibold mb-3 mt-6">Project Structure</h3>
<p class="text-gray-600 mb-4">
Our application will have the following structure:
</p>
<pre class="bg-gray-100 p-4 rounded mb-4"><code class="language-bash">app/
├── Controllers/
│ └── TodoController.php
├── Models/
│ └── Todo.php
├── Events/
│ ├── TodoCreatedEvent.php
│ └── TodoCompletedEvent.php
├── Database/
│ └── Migrations/
│ └── CreateTodosTable.php
├── Repositories/
│ └── TodoRepository.php
└── tests/
└── TodoTest.php</code></pre>
<h3 class="text-lg font-semibold mb-3 mt-6">Environment Configuration</h3>
<p class="text-gray-600 mb-4">
Ensure your <code class="bg-gray-100 px-2 py-1 rounded">.env</code> file is configured with
database settings:
</p>
<pre class="bg-gray-100 p-4 rounded mb-4"><code class="language-bash">DB_DRIVER=sqlite
DB_DATABASE=storage/database/todos.sqlite
APP_DEBUG=true
APP_ENV=local</code></pre>
</section>
<!-- Database & Models -->
<section id="database-models" class="section-anchor mb-12">
<h2 class="text-2xl font-bold text-gray-900 mb-4">Database & Models</h2>
<p class="text-gray-600 mb-6">
Let's start by creating our database schema and model for todos.
</p>
<h3 class="text-lg font-semibold mb-3">Creating the Migration</h3>
<p class="text-gray-600 mb-4">
First, we'll create a migration for the todos table. Create <code
class="bg-gray-100 px-2 py-1 rounded">app/Database/Migrations/2025_01_01_000000_CreateTodosTable.php</code>:
</p>
<pre class="bg-gray-100 p-4 rounded mb-4"><code class="language-php"><?php
declare(strict_types=1);
namespace App\Database\Migrations;
use App\Modules\ForgeAuth\Models\User;
use App\Modules\ForgeDatabaseSQL\DB\Attributes\BelongsTo;
use App\Modules\ForgeDatabaseSQL\DB\Attributes\Column;
use App\Modules\ForgeDatabaseSQL\DB\Attributes\Index;
use App\Modules\ForgeDatabaseSQL\DB\Attributes\Table;
use App\Modules\ForgeDatabaseSQL\DB\Attributes\Timestamps;
use App\Modules\ForgeDatabaseSQL\DB\Enums\ColumnType;
use App\Modules\ForgeDatabaseSQL\DB\Migrations\Migration;
#[Table(name: 'todos')]
#[BelongsTo(related: User::class)]
#[Index(columns: ['user_id'], name: 'idx_todos_user_id')]
#[Index(columns: ['completed'], name: 'idx_todos_completed')]
#[Timestamps]
class CreateTodosTable extends Migration
{
#[Column(name: 'id', type: ColumnType::INTEGER, primaryKey: true, autoIncrement: true)]
public readonly int $id;
#[Column(name: 'user_id', type: ColumnType::INTEGER, nullable: false)]
public readonly int $userId;
#[Column(name: 'title', type: ColumnType::STRING, nullable: false, length: 255)]
public readonly string $title;
#[Column(name: 'description', type: ColumnType::TEXT, nullable: true)]
public readonly ?string $description;
#[Column(name: 'completed', type: ColumnType::BOOLEAN, default: false)]
public readonly bool $completed;
}</code></pre>
<h3 class="text-lg font-semibold mb-3 mt-6">Running the Migration</h3>
<p class="text-gray-600 mb-4">
Run the migration to create the todos table:
</p>
<pre
class="bg-gray-100 p-4 rounded mb-4"><code class="language-bash">php forge.php db:migrate --type=app</code></pre>
<h3 class="text-lg font-semibold mb-3 mt-6">Creating the Todo Model</h3>
<p class="text-gray-600 mb-4">
Now let's create our Todo model. Create <code
class="bg-gray-100 px-2 py-1 rounded">app/Models/Todo.php</code>:
</p>
<pre class="bg-gray-100 p-4 rounded mb-4"><code class="language-php"><?php
declare(strict_types=1);
namespace App\Models;
use App\Modules\ForgeSqlOrm\ORM\Attributes\Column;
use App\Modules\ForgeSqlOrm\ORM\Attributes\ProtectedFields;
use App\Modules\ForgeSqlOrm\ORM\Attributes\Table;
use App\Modules\ForgeSqlOrm\ORM\Model;
use App\Modules\ForgeSqlOrm\Traits\HasMetaData;
use App\Modules\ForgeSqlOrm\Traits\HasTimeStamps;
#[Table("todos")]
#[ProtectedFields("id", "user_id", "created_at", "updated_at")]
class Todo extends Model
{
use HasTimeStamps;
use HasMetaData;
#[Column]
public int $user_id;
#[Column]
public string $title;
#[Column]
public ?string $description;
#[Column]
public bool $completed = false;
public function toggle(): void
{
$this->completed = !$this->completed;
$this->save();
}
public function markAsComplete(): void
{
$this->completed = true;
$this->save();
}
public function markAsIncomplete(): void
{
$this->completed = false;
$this->save();
}
}</code></pre>
<h3 class="text-lg font-semibold mb-3 mt-6">Creating a Repository</h3>
<p class="text-gray-600 mb-4">
Let's create a repository for todo operations. Create <code
class="bg-gray-100 px-2 py-1 rounded">app/Repositories/TodoRepository.php</code>:
</p>
<pre class="bg-gray-100 p-4 rounded mb-4"><code class="language-php"><?php
declare(strict_types=1);
namespace App\Repositories;
use App\Dto\CreateTodoDTO;
use App\Models\Todo;
use App\Modules\ForgeSqlOrm\ORM\RecordRepository;
class TodoRepository extends RecordRepository
{
protected string $model = Todo::class;
public function create(CreateTodoDTO $dto, int $userId): Todo
{
return parent::create([
'user_id' => $userId,
'title' => $dto->title,
'description' => $dto->description,
'completed' => $dto->completed,
]);
}
public function findByUserId(int $userId): array
{
return $this->query()
->where('user_id', $userId)
->orderBy('created_at', 'DESC')
->get();
}
public function findIncompleteByUserId(int $userId): array
{
return $this->query()
->where('user_id', $userId)
->where('completed', false)
->orderBy('created_at', 'DESC')
->get();
}
public function findCompleteByUserId(int $userId): array
{
return $this->query()
->where('user_id', $userId)
->where('completed', true)
->orderBy('created_at', 'DESC')
->get();
}
}</code></pre>
<p class="text-gray-600 mb-4">
The repository extends <code class="bg-gray-100 px-2 py-1 rounded">RecordRepository</code>,
which provides a base <code class="bg-gray-100 px-2 py-1 rounded">create()</code> method
that accepts an array. We've added a type-safe <code
class="bg-gray-100 px-2 py-1 rounded">create()</code> method that accepts a <code
class="bg-gray-100 px-2 py-1 rounded">CreateTodoDTO</code> and user ID, which internally
calls the parent method with the properly structured data. This provides better type safety
and ensures consistent data structure.
</p>
</section>
<!-- Authentication -->
<section id="authentication" class="section-anchor mb-12">
<h2 class="text-2xl font-bold text-gray-900 mb-4">Authentication</h2>
<p class="text-gray-600 mb-6">
We'll use ForgeAuth to handle user authentication. The module should already be installed
and configured.
</p>
<h3 class="text-lg font-semibold mb-3">Using ForgeAuth</h3>
<p class="text-gray-600 mb-4">
ForgeAuth provides authentication routes out of the box. Users can register and login at:
</p>
<ul class="list-disc list-inside space-y-2 text-gray-600 mb-4">
<li><code class="bg-gray-100 px-2 py-1 rounded">/auth/register</code> - User registration
</li>
<li><code class="bg-gray-100 px-2 py-1 rounded">/auth/login</code> - User login</li>
<li><code class="bg-gray-100 px-2 py-1 rounded">/auth/logout</code> - User logout</li>
</ul>
<h3 class="text-lg font-semibold mb-3 mt-6">Getting the Current User</h3>
<p class="text-gray-600 mb-4">
In your controllers, you can get the current authenticated user using the ForgeAuthService:
</p>
<pre class="bg-gray-100 p-4 rounded mb-4"><code class="language-php">use App\Modules\ForgeAuth\Services\ForgeAuthService;
public function __construct(
private readonly ForgeAuthService $auth,
) {}
public function index(): Response
{
$user = $this->auth->user();
if ($user === null) {
return Redirect::to('/auth/login');
}
// Use $user->id to get the user's ID
}</code></pre>
<h3 class="text-lg font-semibold mb-3 mt-6">Protecting Routes</h3>
<p class="text-gray-600 mb-4">
Use the AuthMiddleware to protect routes that require authentication. It's best practice to
apply middleware at the class level when all methods require the same middleware:
</p>
<pre class="bg-gray-100 p-4 rounded mb-4"><code class="language-php">use App\Modules\ForgeAuth\Middlewares\AuthMiddleware;
use Forge\Core\Http\Attributes\Middleware;
#[Service]
#[Middleware("web")]
#[Middleware("App\Modules\ForgeAuth\Middlewares\AuthMiddleware")]
final class TodoController
{
// All methods in this controller require authentication
#[Route("/todos")]
public function index(): Response
{
// This route requires authentication
}
}</code></pre>
<p class="text-gray-600 mb-4">
This approach is cleaner than repeating the middleware attribute on each method, and ensures
all routes in the controller are protected.
</p>
</section>
<!-- Data Transfer Objects -->
<section id="data-transfer-objects" class="section-anchor mb-12">
<h2 class="text-2xl font-bold text-gray-900 mb-4">Data Transfer Objects (DTOs)</h2>
<p class="text-gray-600 mb-6">
Before creating our controller, let's create a DTO (Data Transfer Object) for creating
todos. DTOs provide several benefits:
</p>
<ul class="list-disc list-inside space-y-2 text-gray-600 mb-6">
<li><strong>Type Safety:</strong> DTOs enforce type checking and ensure data integrity</li>
<li><strong>Validation:</strong> Centralized validation logic for input data</li>
<li><strong>Documentation:</strong> Clear contract of what data is expected</li>
<li><strong>Maintainability:</strong> Changes to data structure are isolated to the DTO</li>
<li><strong>Security:</strong> Prevents mass assignment vulnerabilities by explicitly
defining allowed fields</li>
</ul>
<h3 class="text-lg font-semibold mb-3">Creating CreateTodoDTO</h3>
<p class="text-gray-600 mb-4">
Create <code class="bg-gray-100 px-2 py-1 rounded">app/Dto/CreateTodoDTO.php</code>:
</p>
<pre class="bg-gray-100 p-4 rounded mb-4"><code class="language-php"><?php
declare(strict_types=1);
namespace App\Dto;
final class CreateTodoDTO
{
public function __construct(
public string $title,
public ?string $description = null,
public bool $completed = false,
) {
}
public static function fromArray(array $data): self
{
return new self(
title: (string)($data['title'] ?? ''),
description: isset($data['description']) && $data['description'] !== ''
? (string)$data['description']
: null,
completed: isset($data['completed']) && (bool)$data['completed'],
);
}
public function toArray(): array
{
return [
'title' => $this->title,
'description' => $this->description,
'completed' => $this->completed,
];
}
}</code></pre>
<p class="text-gray-600 mb-4">
This DTO defines the structure for creating a todo. The <code
class="bg-gray-100 px-2 py-1 rounded">fromArray()</code> method safely converts request
data into a typed DTO instance, while <code
class="bg-gray-100 px-2 py-1 rounded">toArray()</code> converts it back to an array for
database operations.
</p>
</section>
<!-- Controllers & Routes -->
<section id="controllers-routes" class="section-anchor mb-12">
<h2 class="text-2xl font-bold text-gray-900 mb-4">Controllers & Routes</h2>
<p class="text-gray-600 mb-6">
Now let's create our TodoController with full CRUD operations. We'll use descriptive method
names (not Laravel-style) and follow best practices by using DTOs and the repository
pattern.
</p>
<h3 class="text-lg font-semibold mb-3">Creating TodoController</h3>
<p class="text-gray-600 mb-4">
Create <code
class="bg-gray-100 px-2 py-1 rounded">app/Controllers/TodoController.php</code>:
</p>
<pre class="bg-gray-100 p-4 rounded mb-4"><code class="language-php"><?php
declare(strict_types=1);
namespace App\Controllers;
use App\Dto\CreateTodoDTO;
use App\Events\TodoCompletedEvent;
use App\Events\TodoCreatedEvent;
use App\Modules\ForgeAuth\Middlewares\AuthMiddleware;
use App\Modules\ForgeAuth\Services\ForgeAuthService;
use App\Modules\ForgeEvents\Services\EventDispatcher;
use App\Modules\ForgeWire\Attributes\Action;
use App\Modules\ForgeWire\Attributes\Reactive;
use App\Modules\ForgeWire\Attributes\State;
use App\Repositories\TodoRepository;
use Forge\Core\DI\Attributes\Service;
use Forge\Core\Helpers\Flash;
use Forge\Core\Helpers\Redirect;
use Forge\Core\Http\Attributes\Middleware;
use Forge\Core\Http\Request;
use Forge\Core\Http\Response;
use Forge\Core\Routing\Route;
use Forge\Traits\ControllerHelper;
use Forge\Traits\SecurityHelper;
#[Reactive]
#[Middleware("web")]
#[Middleware("App\Modules\ForgeAuth\Middlewares\AuthMiddleware")]
final class TodoController
{
use ControllerHelper;
use SecurityHelper;
#[State]
public string $newTodoTitle = '';
#[State]
public string $newTodoDescription = '';
public function __construct(
private readonly ForgeAuthService $auth,
private readonly TodoRepository $repository,
private readonly EventDispatcher $dispatcher,
) {}
#[Action]
public function addTodoReactive(): void
{
if (trim($this->newTodoTitle) === '') return;
$user = $this->auth->user();
$dto = new CreateTodoDTO(
title: $this->newTodoTitle,
description: $this->newTodoDescription ?: null
);
$todo = $this->repository->create($dto, $user->id);
$this->dispatcher->dispatch(
new TodoCreatedEvent(
todoId: $todo->id,
userId: $user->id,
title: $todo->title
)
);
$this->newTodoTitle = '';
$this->newTodoDescription = '';
}
#[Action]
public function toggleTodoReactive(int $id): void
{
$user = $this->auth->user();
$todo = $this->repository->find($id);
if ($todo && $todo->user_id === $user->id) {
$todo->toggle();
if ($todo->completed) {
$this->dispatcher->dispatch(
new TodoCompletedEvent(
todoId: $todo->id,
userId: $user->id,
title: $todo->title
)
);
}
}
}
#[Action]
public function deleteTodoReactive(int $id): void
{
$user = $this->auth->user();
$todo = $this->repository->find($id);
if ($todo && $todo->user_id === $user->id) {
$this->repository->delete($todo);
}
}
#[Route("/todos")]
public function index(): Response
{
$user = $this->auth->user();
$todos = $this->repository->findByUserId($user->id);
return $this->view("todos/index", [
"todos" => $todos,
"user" => $user,
"total" => $this->total,
"number1" => $this->number1,
"number2" => $this->number2,
]);
}
#[Route("/todos", "POST")]
public function createTodo(Request $request): Response
{
$user = $this->auth->user();
$todoData = $this->sanitize($request->postData);
$data = [
'user_id' => $user->id,
...$todoData
];
if (empty($data['title'])) {
Flash::set("error", "Title is required");
return Redirect::to("/todos");
}
$dto = CreateTodoDTO::fromArray($data);
$todo = $this->repository->create($dto, $user->id);
Flash::set("success", "Todo created successfully");
$this->dispatcher->dispatch(
new TodoCreatedEvent(
todoId: $todo->id,
userId: $user->id,
title: $todo->title
)
);
return Redirect::to("/todos");
}
#[Route("/todos/{id}", "PATCH")]
public function updateTodo(Request $request, string $id): Response
{
$user = $this->auth->user();
$todo = $this->repository->find((int)$id);
if ($todo === null || $todo->user_id !== $user->id) {
Flash::set("error", "Todo not found");
return Redirect::to("/todos");
}
$data = $this->sanitize($request->postData);
$updateData = [];
if (isset($data['title'])) {
$updateData['title'] = $data['title'];
}
if (isset($data['description'])) {
$updateData['description'] = $data['description'];
}
if (isset($data['completed'])) {
$updateData['completed'] = (bool)$data['completed'];
}
if (!empty($updateData)) {
$this->repository->update($todo, $updateData);
}
Flash::set("success", "Todo updated successfully");
return Redirect::to("/todos");
}
#[Route("/todos/{id}/toggle", "POST")]
public function toggle(string $id): Response
{
$user = $this->auth->user();
$todo = $this->repository->find((int)$id);
if ($todo === null || $todo->user_id !== $user->id) {
Flash::set("error", "Todo not found");
return Redirect::to("/todos");
}
$todo->toggle();
Flash::set("success", "Todo " . ($todo->completed ? "completed" : "marked as incomplete"));
if ($todo->completed) {
$this->dispatcher->dispatch(
new TodoCompletedEvent(
todoId: $todo->id,
userId: $user->id,
title: $todo->title
)
);
}
return Redirect::to("/todos");
}
#[Route("/todos/{id}", "DELETE")]
public function deleteTodo(string $id): Response
{
$user = $this->auth->user();
$todo = $this->repository->find((int)$id);
if ($todo === null || $todo->user_id !== $user->id) {
Flash::set("error", "Todo not found");
return Redirect::to("/todos");
}
$this->repository->delete($todo);
Flash::set("success", "Todo deleted successfully");
return Redirect::to("/todos");
}
}</code></pre>
<h3 class="text-lg font-semibold mb-3 mt-6">Route Attributes</h3>
<p class="text-gray-600 mb-4">
The <code class="bg-gray-100 px-2 py-1 rounded">#[Route]</code> attribute defines routes:
</p>
<ul class="list-disc list-inside space-y-2 text-gray-600 mb-4">
<li><code class="bg-gray-100 px-2 py-1 rounded">#[Route("/todos")]</code> - GET route</li>
<li><code class="bg-gray-100 px-2 py-1 rounded">#[Route("/todos", "POST")]</code> - POST
route</li>
<li><code class="bg-gray-100 px-2 py-1 rounded">#[Route("/todos/{id}", "PATCH")]</code> -
PATCH route with parameter</li>
<li><code class="bg-gray-100 px-2 py-1 rounded">#[Route("/todos/{id}", "DELETE")]</code> -
DELETE route</li>
</ul>
</section>
<!-- Views & Layouts -->
<section id="views-layouts" class="section-anchor mb-12">
<h2 class="text-2xl font-bold text-gray-900 mb-4">Views & Layouts</h2>
<p class="text-gray-600 mb-6">
Let's create the views for our todo application.
</p>
<h3 class="text-lg font-semibold mb-3">Creating the Layout</h3>
<p class="text-gray-600 mb-4">
First, create a layout file at <code
class="bg-gray-100 px-2 py-1 rounded">app/resources/views/layouts/todos.php</code>:
</p>
<pre class="bg-gray-100 p-4 rounded mb-4"><code class="language-php"><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title><?= e($title ?? 'Todos') ?></title>
<link rel="stylesheet" href="/assets/css/app.css">
<?= csrf_meta() ?>
<?= window_csrf_token() ?>
</head>
<body class="bg-gray-50">
<nav class="bg-white shadow-sm mb-8">
<div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
<div class="flex justify-between h-16">
<div class="flex items-center">
<a href="/todos" class="text-xl font-bold text-gray-900">Todo App</a>
</div>
<div class="flex items-center space-x-4">
<span class="text-gray-600"><?= e($user->email ?? 'Guest') ?></span>
<a href="/auth/logout" class="text-blue-600 hover:text-blue-800">Logout</a>
</div>
</div>
</div>
</nav>
<main class="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8">
<?php if (Flash::has('success')): ?>
<div class="bg-green-50 border border-green-200 text-green-800 px-4 py-3 rounded mb-4">
<?= e(Flash::get('success')) ?>
</div>
<?php endif; ?>
<?php if (Flash::has('error')): ?>
<div class="bg-red-50 border border-red-200 text-red-800 px-4 py-3 rounded mb-4">
<?= e(Flash::get('error')) ?>
</div>
<?php endif; ?>
<?= $content ?>
</main>
</body>
</html></code></pre>
<h3 class="text-lg font-semibold mb-3 mt-6">Creating the Todos Index View</h3>
<p class="text-gray-600 mb-4">
Create <code
class="bg-gray-100 px-2 py-1 rounded">app/resources/views/todos/index.php</code>:
</p>
<pre class="bg-gray-100 p-4 rounded mb-4"><code class="language-php"><?php layout('todos'); ?>
<div class="bg-white rounded-lg shadow p-6">
<h1 class="text-2xl font-bold mb-6">My Todos</h1>
<!-- Create Todo Form -->
<form method="POST" action="/todos" class="mb-6">
<?= csrf_input() ?>
<div class="flex gap-4">
<input
type="text"
name="title"
placeholder="Todo title..."
required
class="flex-1 px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
>
<input
type="text"
name="description"
placeholder="Description (optional)"
class="flex-1 px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
>
<button
type="submit"
class="px-6 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700"
>
Add Todo
</button>
</div>
</form>
<!-- Todos List -->
<div class="space-y-3">
<?php foreach ($todos as $todo): ?>
<div class="flex items-center gap-4 p-4 border border-gray-200 rounded-md <?= $todo->completed ? 'bg-gray-50 opacity-75' : 'bg-white' ?>">
<div class="flex-1">
<h3 class="font-semibold <?= $todo->completed ? 'line-through text-gray-500' : 'text-gray-900' ?>">
<?= e($todo->title) ?>
</h3>
<?php if ($todo->description): ?>
<p class="text-sm text-gray-600 mt-1"><?= e($todo->description) ?></p>
<?php endif; ?>
</div>
<form method="POST" action="/todos/<?= $todo->id ?>/toggle" class="inline">
<?= csrf_input() ?>
<button
type="submit"
class="px-4 py-2 <?= $todo->completed ? 'bg-yellow-600' : 'bg-green-600' ?> text-white rounded-md hover:opacity-80"
>
<?= $todo->completed ? 'Undo' : 'Complete' ?>
</button>
</form>
<form method="POST" action="/todos/<?= $todo->id ?>" class="inline">
<?= csrf_input() ?>
<input type="hidden" name="_method" value="DELETE">
<button
type="submit"
class="px-4 py-2 bg-red-600 text-white rounded-md hover:bg-red-700"
onclick="return confirm('Are you sure?')"
>
Delete
</button>
</form>
</div>
<?php endforeach; ?>
<?php if (empty($todos)): ?>
<p class="text-gray-500 text-center py-8">No todos yet. Create your first todo above!</p>
<?php endif; ?>
</div>
</div></code></pre>
</section>
<!-- ForgeWire Components -->
<section id="forgewire" class="section-anchor mb-12">
<h2 class="text-2xl font-bold text-gray-900 mb-4">ForgeWire: Real-Time Reactivity</h2>
<p class="text-gray-600 mb-6">
Now for the magic. We'll add ForgeWire to our <code>TodoController</code> to make it
reactive. This means changes will happen instantly in the browser without full page
refreshes, yet all logic remains securely on the server.
</p>
<h3 class="text-lg font-semibold mb-3">1. Making the Controller Reactive</h3>
<p class="text-gray-600 mb-4">
We don't need to create a new class. We simply add the <code>#[Reactive]</code> attribute to
our existing <code>TodoController</code> and mark the data we want to persist between
updates with <code>#[State]</code>.
</p>
<div class="code-block p-6 text-white rounded-lg mb-6">
<pre><code class="language-php">#[Reactive] // Enable reactivity
#[Service]
#[Middleware("web")]
#[Middleware("App\Modules\ForgeAuth\Middlewares\AuthMiddleware")]
final class TodoController
{
use ControllerHelper;
// These values will be preserved in the session between reactive updates
#[State]
public string $newTodoTitle = '';
#[State]
public string $newTodoDescription = '';
#[Action] // Can be called from the frontend via fw:click
public function addTodoReactive(): void
{
if (empty($this->newTodoTitle)) return;
$user = $this->auth->user();
$dto = new CreateTodoDTO(
title: $this->newTodoTitle,