I'm a beginner in OOP and PHP frameworks. I used slim skeleton to create a project and designed the project in this way.
Project structure is given by the slim skeleton. Object Mappers are added by my self. I want to know whether this is a good practice. What I'm doing wrong here. Is there any better way to do this?
src
Controllers
PostController.php
CommentController.php
Models
Post.php
Comment.php
ObjectMappers
PostMapper.php
CommentMapper.php
Dependencies.php
Middleware.php
Routes.php
Settings.php
Model files are used to include queries for relevant class. Mappers are the real classes that used to map query results to necessary class. Controllers are for necessary operations before sending it to the user.
Post.php
namespace App\Models;
class Post {
public function getPostById($id){
$sql = "SELECT `post_id`, `post` FROM `posts` WHERE `post_id` = :id";
try {
$stmt = $this->db->prepare($sql);
$stmt->execute(['id' => $id]);
$post = $stmt->fetchObject('\App\ObjectMappers\PostMapper');
if($post){
return $post;
}
return false;
} catch (\PDOException $e){
return false;
}
}
// Other queries
}
PostMapper.php
namespace App\ObjectMappers;
class PostObject {
public $post_id;
public $post;
public function __construct(){}
public function getPost_id()
{
return $this->post_id;
}
public function setPost_id($post_id)
{
$this->post_id= $post_id;
return $this;
}
public function getPost()
{
return $this->post;
}
public function setPost($post)
{
$this->post= $post;
return $this;
}
}
PostController.php
namespace App\Controllers;
class PostController {
public function ($request, $response, $args){
$postId = $request->getAttribute("post_id");
if(!$postId){
return $response->withJSON("post id not found");
}
$post = $this->Post->getPostById($postId);
if(!$post ){
return $response->withJSON("post not found");
}
return $response->withJSON($post);
}
}
I'll be glad if you can help me. I'm trying to avoid using existing ORMs here.