<?php
namespace App\Controllers;
use App\BaseController;
use App\Request;
class DashboardController extends BaseController {
public function index(Request $request): void
{
$this->view->render("dashboard",
[
"user" => $this->user
]
);
}
}
<?php
namespace App\Controllers;
use App\BaseController;
use App\Request;
class HomeController extends BaseController {
public function index(Request $request): void
{
$this->view->render("home");
}
}
<?php
namespace App\Controllers;
use App\BaseController;
use App\Request;
class LoginController extends BaseController
{
public function index(Request $request)
{
if($this->user->isLoggedIn()) {
$this->redirectTo(path: "dashboard");
}
if ($request->getMethod() != "POST") {
$this->view->render("login");
return;
}
try {
$inputForm = $request->getInput();
$this->user->login($inputForm);
$this->redirectTo(path: "dashboard");
} catch (\Throwable $th) {
throw $th;
}
}
}
<?php
namespace App\Helpers;
class Str
{
public static function toPascalCase(string $subject): string
{
return str_replace('_', '', ucwords($subject, '_'));
}
public static function toCamelCase(string $subject): string
{
return lcfirst(self::toPascalCase($subject));
}
}
<?php
namespace App\Models;
use PDO;
use PDOStatement;
class Database
{
private $host = "localhost";
private $dbname = "forum";
private $username = "root";
private $password = "";
private PDO $db;
private PDOStatement $statement;
public function __construct()
{
$this->db = new PDO(
dsn: "mysql:host={$this->host};dbname={$this->dbname}",
username: $this->username,
password: $this->password
);
}
public function query($sql,$values=[]): static {
$this->statement = $this->db->prepare(query: $sql);
$this->statement->execute(params: $values);
return $this;
}
public function results():array {
return $this->statement->fetchAll(PDO::FETCH_ASSOC);
}
public function first():array {
return $this->results()[0];
}
public function count():int {
return $this->statement->rowCount();
}
}
<?php
namespace App\Models;
use App\Helpers\Str;
class User
{
private Database $db;
private $id;
private $email;
private $firstName;
private $lastName;
private $password;
public function __construct(Database $db)
{
$this->db = $db;
}
public function find(string|int $identifier): bool
{
$column = is_int(value: $identifier) ? "id" : "email";
$sql = "SELECT * FROM `users` WHERE `{$column}` = :identifier";
$userQuery = $this->db->query($sql, ["identifier" => $identifier]);
if (!$userQuery->count()) return false;
$userData = $userQuery->first();
foreach ($userData as $column => $value) {
$columnCamel = Str::toCamelCase($column);
$this->{$columnCamel} = $value;
}
return true;
}
public function isLoggedIn(): bool {
return isset($_SESSION['userId']);
}
public function login(array $userData): void
{
if (!$this->find($userData["email"])) {
throw new \Exception(message: "Email Not Corrent 😌");
}
$_SESSION['userId'] = $this->getId();
}
public function getId(): int
{
return (int)($this->id ?? $_SESSION['userId']);
}
public function getFirstName():string {
return $this->firstName;
}
}
<?php
namespace App;
class App
{
public function __construct()
{
$router = new Router();
$requestedControlller = $router->getRequestedController();
$requestedMethod = $router->getRequestedMethod();
$controller = new $requestedControlller();
$params = $router->getParams();
$request = new Request(pageParams: $params);
$controller->{$requestedMethod}($request);
}
}
<?php
namespace App;
use App\Models\Database;
use App\Models\User;
abstract class BaseController {
protected View $view;
protected User $user;
protected Database $db;
public function __construct() {
$this->db = new Database();
$this->user = new User(db: $this->db);
$this->view = new View(user: $this->user);
if ($this->user->isLoggedIn()) {
$this->user->find($this->user->getId());
}
}
abstract public function index(Request $request);
public function redirectTo(string $path): never {
header(header: "Location:".$path);
exit();
}
}
<?php
namespace App;
class Request {
private $pageParams;
private $getParams;
private $postParams;
private $fileParams;
public function __construct($pageParams) {
$this->pageParams = $pageParams;
$this->getParams = $_GET;
$this->postParams = $_POST;
$this->fileParams = $_FILES;
}
public function getMethod(): string {
return $_SERVER['REQUEST_METHOD'];
}
public function getInput(string $kind="post") {
$input = match($kind) {
"page" => $this->pageParams,
"get" => $this->getParams,
"post" => $this->postParams,
"file" => $this->fileParams
};
return $input;
}
}
<?php
namespace App;
use App\Controllers\HomeController;
class Router {
private $controller = HomeController::class;
private $method = "index";
private $params = [];
public function __construct() {
$url = $this->parseUrl();
if(!isset($url[0])) return;
$requestedController = "App\\Controllers\\" . ucfirst(string: $url[0]) . "Controller";
$this->controller = $requestedController;
}
public function getRequestedController(): string {
return $this->controller;
}
public function getRequestedMethod(): string {
return $this->method;
}
public function getParams(): array {
return $this->params;
}
public function parseUrl(): array {
if(!isset($_GET['url'])) return [];
$url = rtrim(string: $_GET['url'], characters: "/");
$url = explode(separator: "/",string: $url);
return $url;
}
}
<?php
namespace App;
use App\Models\User;
class View {
private User $user;
public function __construct(User $user) {
$this->user = $user;
}
public function render(string $view,$data=[]): void {
extract($data);
require_once("../app/views/partials/header.php");
require_once("../app/views/{$view}.php");
require_once("../app/views/partials/footer.php");
}
}
<?php
class App
{
protected $controller = 'homeController';
protected $method = 'index';
protected $params = [];
public function __construct()
{
$url = $this->parseURL();
if (file_exists(filename: '../app/controllers/' . $url[0] . '.php')) {
$this->controller = $url[0];
unset($url[0]);
} else {
die("{$url[0]} not found");
}
require_once '../app/controllers/' . $this->controller . '.php';
$this->controller = new $this->controller;
if (isset($url[1])) {
if (method_exists(object_or_class: $this->controller, method: $url[1])) {
$this->method = $url[1];
unset($url[1]);
}
}
if (!empty($url)) {
$this->params = array_values(array: $url);
}
}
public function parseURL()
{
if (isset($_GET['url'])) {
$url = explode(separator: '/', string: filter_var(value: trim(string: $_GET['url']), filter: FILTER_SANITIZE_URL));
$url[0] = $url[0] . 'Controller';
} else {
$url[0] = 'homeController';
}
return $url;
}
public function run()
{
return call_user_func_array(callback: [$this->controller, $this->method], args: $this->params);
}
}
<?php
class Controller
{
public function view($view, $data = [])
{
require_once '../app/views/' . $view . '.php';
}
public function model($model)
{
require_once '../app/models/' . $model . '.php';
return new $model;
}
public function redirect($url)
{
header('Location: ' . BASEURL . '/' . $url);
exit;
}
}
<?php
class homeController extends Controller
{
public function index(): void
{
$data['title'] = 'Lionel Home';
echo $data['title'];
}
}
<?php
class mahasiswaController extends Controller {
public function index() {
$data['title'] = 'Halaman mahasiswa';
$data['judul'] = 'Data mahasiswa';
$data['mahasiswa'] = $this->model('Mahasiswa')->getAll();
$this->view('templates/header', $data);
$this->view('mahasiswa/index', $data);
$this->view('templates/footer');
}
}
<?php
class App
{
protected $controller = 'homeController';
protected $method = 'index';
protected $params = [];
public function __construct()
{
$url = $this->parseURL();
if (file_exists(filename: '../app/controllers/' . $url[0] . '.php')) {
$this->controller = $url[0];
unset($url[0]);
} else {
die("{$url[0]} not found");
}
require_once '../app/controllers/' . $this->controller . '.php';
$this->controller = new $this->controller;
if (isset($url[1])) {
if (method_exists(object_or_class: $this->controller, method: $url[1])) {
$this->method = $url[1];
unset($url[1]);
}
}
if (!empty($url)) {
$this->params = array_values(array: $url);
}
}
public function parseURL()
{
if (isset($_GET['url'])) {
$url = explode(separator: '/', string: filter_var(value: trim(string: $_GET['url']), filter: FILTER_SANITIZE_URL));
$url[0] = $url[0] . 'Controller';
} else {
$url[0] = 'homeController';
}
return $url;
}
public function run()
{
return call_user_func_array(callback: [$this->controller, $this->method], args: $this->params);
}
}
<?php
class Controller
{
public function view($view, $data = [])
{
require_once '../app/views/' . $view . '.php';
}
public function model($model)
{
require_once '../app/models/' . $model . '.php';
return new $model;
}
public function redirect($url)
{
header('Location: ' . BASEURL . '/' . $url);
exit;
}
}
<?php
class Database {
private $host = DB_HOST;
private $dbname = DB_NAME;
private $username = DB_USER;
private $password = DB_PASS;
private $db;
private $st;
public function __construct()
{
try {
$this->db = new PDO(dsn: "mysql:host={$this->host};dbname={$this->dbname}", username: $this->username, password: $this->password);
} catch (PDOException $e) {
print_r(value: $e->getMessage());
die;
}
}
public function query($query): void
{
$this->st = $this->db->prepare($query);
}
public function execute(): void
{
$this->st->execute();
}
public function resultSet(): array
{
$this->execute();
return $this->st->fetchAll(PDO::FETCH_ASSOC);
}
public function single(): array
{
$this->execute();
return $this->st->fetch(PDO::FETCH_ASSOC);
}
}
<?php
class Mahasiswa {
private $db;
private $table = 'mahasiswa';
public function __construct()
{
$this->db = new Database;
}
public function getAll()
{
$this->db->query("SELECT * FROM {$this->table}");
return $this->db->resultSet();
}
}