I made an MVC framework for training, and I get this error and I’m not sure what is wrong with my function.
when I open link like this : http://mvctrav.com/posts/show/6 it show me the post but when deleting the id like this http://mvctrav.com/posts/show/ it shows me the error
My error looks like this:
JavaScript
x
Fatal error: Uncaught ArgumentCountError: Too few arguments to function Posts::show(), 0 passed in C:xampphtdocstravapplibrariesCore.php on line 51 and exactly 1 expected in C:xampphtdocstravappcontrollersPosts.php:124 Stack trace: #0 C:xampphtdocstravapplibrariesCore.php(51): Posts->show() #1 C:xampphtdocstravpublicindex.php(4): Core->__construct() #2 {main} thrown in C:xampphtdocstravappcontrollersPosts.php on line 124
and my function is :
JavaScript
public function show($id)
{
$post = $this->postModel->getPostById($id);
$user = $this->userModel->getUserById($post->user_id);
$data = [
'post' => $post,
'user' => $user
];
$this->view('posts/show', $data);
}
this is my Core class:
JavaScript
<?php
class Core
{
protected $currentController = 'Pages';
protected $currentMethod = 'index';
protected $params = [];
public function __construct()
{
//print_r($this->getUrl());
$url = $this->getUrl();
// Look in controllers for first value
if (file_exists('../app/controllers/' . ucwords($url[0]) . '.php')) {
// If exists, set as controller
$this->currentController = ucwords($url[0]);
// Unset 0 Index
unset($url[0]);
}
// Require the controller
require_once '../app/controllers/' . $this->currentController . '.php';
// Instantiate controller class
$this->currentController = new $this->currentController;
// Check for second part of url
if (isset($url[1])) {
// Check to see if method exists in controller
if (method_exists($this->currentController, $url[1])) {
$this->currentMethod = $url[1];
// Unset 1 index
unset($url[1]);
}
}
// Get params
$this->params = $url ? array_values($url) : [];
// Call a callback with array of params
call_user_func_array([$this->currentController, $this->currentMethod], $this->params);
}
public function getUrl()
{
$url = isset($_GET['url']) ? $_GET['url'] : "/";
$url = filter_var(trim($url, "/"), FILTER_SANITIZE_URL);
$url = explode('/', $url);
return $url;
}
}
my problem is: link http://mvctrav.com/posts/show to be not found or redirecting to specific page instead of showing the error Thank you for trying to help!
Advertisement
Answer
I think you need to edit show()
function to be like this:
JavaScript
public function show($id = null)
{
$post = $this->postModel->getPostById($id);
$user = $this->userModel->getUserById($post->user_id);
$data = [
'post' => $post,
'user' => $user
];
if ($user !== false && null !== $id) {
$this->view('posts/show', $data);
} else {
header('Location:'.'404.php');
}
}