1+ <?php
2+
3+ require_once __DIR__ . '/../models/PostModel.php ' ;
4+ require_once __DIR__ . '/../entities/Post.php ' ;
5+ require_once __DIR__ . '/../util/Response.php ' ;
6+
7+ class PostController
8+ {
9+ private PostModel $ post_model ;
10+
11+ public function __construct ()
12+ {
13+ $ this ->post_model = new PostModel ();
14+ }
15+
16+ public function findAll ()
17+ {
18+ $ posts [] = new Post ();
19+ $ posts = $ this ->post_model ->findAll ();
20+
21+ if ($ posts ) {
22+ return json_encode ($ posts );
23+ } else {
24+ return Response::sendWithCode (400 , "no results found " );
25+ }
26+ }
27+
28+ public function findById ($ id )
29+ {
30+ $ post = $ this ->post_model ->findById ($ id );
31+
32+ if ($ post ->getId ()) {
33+ return $ post ->toJson ();
34+ } else {
35+ return Response::sendWithCode (400 , "no results found " );
36+ }
37+ }
38+
39+ public function findByTitle ($ title )
40+ {
41+ $ posts [] = new Post ();
42+ $ posts = $ this ->post_model ->findByTitle ($ title );
43+
44+ if ($ posts ) {
45+ return json_encode ($ posts );
46+ } else {
47+ return Response::sendWithCode (400 , "no results found " );
48+ }
49+ }
50+
51+ public function create ($ data )
52+ {
53+ $ post = new Post ();
54+ $ post ->setCategory ($ data ->category );
55+ $ post ->setTitle ($ data ->title );
56+ $ post ->setBody ($ data ->body );
57+ $ post ->setAuthor ($ data ->author );
58+
59+ if ($ this ->post_model ->create ($ post )) {
60+ return Response::sendWithCode (201 , "new post created " );
61+ } else {
62+ return Response::sendWithCode (500 , "an error " );
63+ }
64+ }
65+
66+ public function update ($ id , $ data )
67+ {
68+ $ post = new Post ();
69+ $ post ->setId ($ id );
70+ $ post ->setCategory ($ data ->category );
71+ $ post ->setTitle ($ data ->title );
72+ $ post ->setBody ($ data ->body );
73+ $ post ->setAuthor ($ data ->author );
74+
75+ if ($ this ->post_model ->update ($ post )) {
76+ return Response::sendWithCode (200 , "post updated " );
77+ } else {
78+ return Response::sendWithCode (500 , "an error " );
79+ }
80+ }
81+
82+ public function delete ($ data )
83+ {
84+ $ post = new Post ();
85+ $ post ->setId ($ data ->id );
86+
87+ if ($ this ->post_model ->delete ($ post )) {
88+ return Response::sendWithCode (204 , "deleted " );
89+ } else {
90+ return Response::sendWithCode (500 , "an error " );
91+ }
92+ }
93+
94+ }
0 commit comments