Hello, tell me if I understood the concept of MVC pattern correctly.
1.The router receives a GET request. There he handles the GET request, including the necessary controller files, models and view, in our case these are news (for example, https://site.ru/news/123 )
class Router { private $routes = array( 'news' => array('newsbyid','newsbycategory'), 'products'); public $url; function __construct() { $this->url = explode('/', trim($_GET['uri'], '/')); } public function run() { if(!empty($this->url)) { if(in_array($controller = $this->url[0], array_keys($this->routes))) { require_once rootdir.'/models/'.$controller.'model.php'; require_once rootdir.'/controllers/'.$controller.'controller.php'; switch (count($this->url)) { case 1: $action = $this->url[0]; break; case 2: $action = $this->routes[$this->url[0]][0]; $arg = $this->url[1]; break; case 3: // break; } call_user_func_array(array($newscontroller, $action), array($arg)); require_once rootdir.'/views/'.$controller.'/view.php'; } else return '404 not found'; } else return 'Main page'; } }
Newscontroller invokes the data retrieval method.
class Newscontroller extends Newsmodel { public $news = array(); public function news() { $this->news = $this->getnews(); } public function newsbyid($id) { $this->news = $this->getnewsbyid($id); } public function newsbycategory($category) { } }
$ newscontroller = new Newscontroller;
We take this news list from a model whose class we inherit.
<?php class Newsmodel { public function getnews() { $count = 2; for ($i=0; $i <$count ; $i++) { $news[$i]['id'] = $i; $news[$i]['title'] = 'title'.$i; $news[$i]['message'] = 'message'.$i; } return $news; } public function getnewsbycategory($category) { } public function getnewsbyid() { $news[0]['id'] = 1; $news[0]['title'] = 'title'; $news[0]['message'] = 'message'; return $news; } } $newsmodel = new Newsmodel; The data is received and processed, and the news class itself is in the news class property. Now in the router (see above) there is require_once rootdir.'/views/'.$controller.'/view.php';
<?php foreach ($newscontroller->news as $news):?> <b><?php echo $news['title']?></b> <div style="font-size: 15px; border: 1px solid red;"><?php echo $news['message'] ?></div> <br><br> <?php endforeach;?> And it turns out the run() router method itself is called in index.php ($router->run() and the user sees the news
Thanks to everyone who was not lazy and read to the end.
That is, to be brief.
1. A user receives a GET request. 2. The router selects the desired type of controller. 3. The controller refers to the model receives data for example from the database 4. And in the view file there is an html markup in which this data will actually be displayed
Контроллер обращается к модели...... yes, the controller can access the model, and your controller inherits from the model - which is wrong - Alexey Shimansky