What is MVC or how to start writing a website? / ~#root -i What is MVC or how to start writing a website? / ~#root -i What is MVC or how to start writing a website? / ~#root -i What is MVC or how to start writing a website? / ~#root -i What is MVC or how to start writing a website? / ~#root -i What is MVC or how to start writing a website? / ~#root -i What is MVC or how to start writing a website? / ~#root -i What is MVC or how to start writing a website? / ~#root -i
  • RU
  • UA
  • EN
  • Create an online store
  • Documentation
  • Blog
    • Unix ОS
    • Php
    • MySQL
    • JavaScript
    • Package Managers
    • Docker
    • Seo
  • Auxiliary services
    • Short Links
    • Exchange views YouTube
  • Sign in
  • Create Account
  • Home
  • Php
  • What is MVC or how to start writing a website?

What is MVC or how to start writing a website?

Don't judge too harshly, to show an example of how MVC works, I wrote a simple code in 20 minutes based on a path split in a link. We will analyze everything using the example of a local link:

http://test1.loc/product/test-product

Our project structure will consist of 4 folders and several php files.

Project folder structure

1. .htaccess:

This is the very first file that fires when a user logs in, back at the apache level.

AddDefaultCharset UTF-8
Options +FollowSymLinks
RewriteEngine on

RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.php?path=$1&%{QUERY_STRING}  [L]

Apache must have mod_rewrite installed.

RewriteRule ^index\.php$ - [L] // - Says that the main startup file is index.php. It is not necessary to specify it in the url now.

RewriteRule ^(.*)$ /index.php?path=$1&%{QUERY_STRING}  [L] // - the entire path (product/test-product) goes into the $_GET parameter, which we will then split into routes.

2. index.php:

This is the startup file where I placed the error handling and the launch of the next step.

<?php

if (strpos($_SERVER['REQUEST_URI'], '.php') !== false) {
    header("Location:http://" . $_SERVER['SERVER_NAME']);
    exit;
}

define('ENVIRONMENT', 'development');

switch (ENVIRONMENT) {
    case 'development':
        error_reporting(E_ALL ^ ​​E_NOTICE ^ E_WARNING);
        ini_set('display_errors', 'on');
        break;

    case 'testing':
    case 'production':
        error_reporting(E_ALL ^ ​​E_NOTICE ^ E_DEPRECATED ^ E_STRICT ^ E_WARNING);
        ini_set('display_errors', 'off');
        break;

    default:
        header('HTTP/1.1 503 Service Unavailable.', TRUE, 503);
        exit('The application environment is not set correctly.');
}

define('DOCUMENT_ROOT', $_SERVER['DOCUMENT_ROOT']);
define('SERVER_NAME ', $_SERVER['SERVER_NAME']);

require_once DOCUMENT_ROOT.'/system/router.php';
new Router();

Here we declare constants and run the class Router();

3. system/router.php:

The main router that divides the link into array segments and starts the controller on the name of the first segment of the link. The first segment of the link is "product". Therefore, product.php

will be loaded

<?php

if (!defined('DOCUMENT_ROOT')) {
    exit('No direct script access allowed');
}    

class Router {
    
    private $full_path ='';
    private $array_path = array();
       
    public function __construct() {
        $this->parse_path();
    }
    
    private function parse_path() {
        $this->full_path = $_GET['path'];
        $this->array_path = explode('/', $_GET['path']);
        unset($_GET['path']);
        
        if (file_exists(DOCUMENT_ROOT . '/controller/'.$this->array_path[0] . '.php')) {
        &nbsp ;   require_once DOCUMENT_ROOT . '/controller/' . $this->array_path[0] . '.php';
            
            if (class_exists($this->array_path[0])) {
                $class = new $this->array_path[0]($this->array_path);
                 $class->index();
            }
        }
    }
    
}

!defined('DOCUMENT_ROOT') - will not let you run the php file directly.

parse_path() - we parse the $_GET['path'] url that comes from htaccess into the file path and run index().

4. controller/product.php:

Controller handler. We will place the logic for processing the model and view in it. The first segment of the link is "product". Therefore, this file is loaded. Further, I think it is clear why "product_model.php" and "product_view.php"

are loaded

<?php

if (!defined('DOCUMENT_ROOT')) {
    exit('No direct script access allowed');
}

/**
 * Calculation and logic processing controller
 */
class product {

    private $array_path = array();

    public function __construct($path) {
        $this->array_path = $path;
    }

    public function index() {
        $dataProduct = $this->connectPhp('model');    
        
        $this->includeFile('view', ['dataProduct' => $dataProduct]);
        
    }

    private function connectPhp($folder) {

        if ($this->includeFile($folder)) {

            if (class_exists($this->array_path[0] . '_' . $folder)) {
           &nbsp ;    $name = $this->array_path[0] . '_' . $folder;
                $class = new $name($this->array_path);
                return $class->index();
            }
        }
    }

    private function includeFile($folder, $data = false) {
        if (file_exists(DOCUMENT_ROOT . '/' . $folder . '/' . $this->array_path[0]. '_' . $folder . '.php')) {

&nbsp ;           include DOCUMENT_ROOT . '/' . $folder. '/' . $this->array_path[0]. '_' . $folder. '.php';
            return TRUE;
            
        }
        return FALSE;
        
    }

}

in index() we connect the model and connect the view, in which we use the received variable $dataProduct.

5. model/product_model.php:

This model will be responsible for processing requests to the database. We will place everything related to connections and requests in it.

<?php

if (!defined('DOCUMENT_ROOT')) {
    exit('No direct script access allowed');
}

/**
 * Model for manipulating database queries
 */< br />class product_model {   
    
    private $array_path = array();
    
    public function __construct($path) {
        $this->array_path = $path;
    }
    
    public function index() {
        $this->dbConnect();
        
        return $this->getProduct();
    }
    
    private function dbConnect() {
        // Connect to the database here
    }
    
    private function getProduct() {
        // Retrieve something related to the product $this->array_path[1];
        return 'Product test test';
    }
    
}

The model is empty, didn't fill it in, just returned a string for an example MVC structure. This also runs index() and returns a string.

6.view/product_view.php:

Html page output. The view itself is formed, which will be available to the user.

<html>
    <head>
        <title>Main Page - About Me</title>
    </head>
    <body>
    <center><h1><?php echo $data['dataProduct']; ?></h1></center>
    <center><h2>Product Description</h2></center>
</body>
</html>

We pass the string that came from the model in the $data array. We output and everything is cool.

As a result, we will have a regular page.

View final output

Do not judge strictly, because I did not set the task to show the correct code or the correct class structure. Found inspiration to explain about MVC.

17 May 18
1392
2

Comments

Файзулла

02 March 2019 20:28
Здравствуйте.
Немного ясно стало, но не совсем... в частности как соединять фронтенд с бакэндом
я хочу сайт сделать на РНР без шаблонизатора и фрэймворка, но в MVC/
Поможете? и вам материал на сайт будет )))
8

root-i

02 March 2019 22:33
Добрый день, Файзулла.
В общем view/product_view.php это и есть подключаемая фронтовая страница.
Для каждого контроллера можно создать свой фронтовый php файл. Можно поиграться с расширением структуры на namespace.
Я привел только стркутурный пример, чтобы показать что такое MVC. Так же есть еще HMVC, но не будем углубляться)
В любом случае тема эта большая и должна исходить из задачи, которую желают видеть в проекте)
Можно разобрать какай-то индивидуальный пример для Вас, отпишите через обратную связь если есть желание)
11
Name
E-mail
Rating
Review

Other articles from the category

25 April 2022

Create and download CSV in PHP

Consider the possibility of quickly creating a CSV file with automatic file download. Consider the formation, separators and header for the ability to download the file.

19 June 2019

ImageCMS Templates 4.10-4.12.1

Latest templates from ImageCMS 4.12, authorization is required to download.

26 January 2019

Long-term storage of the basket in the online store

Consider options for popular options for storing goods in a shopping cart in an online store. Let's outline the pros and cons of such storage. Consider options for long-term storage of the basket.

17 January 2019

License key for ImageCMS 4.9-4.12.1 Pro and Pre

Creating a key for imageCMS 4.9-4.12.1 Pro and Pre. You must be logged in to receive it.

07 December 2018

$_SERVER[DOCUMENT_ROOT] in CLI or Cron

When running the script from the console, there is no DOCUMENT_ROOT in $_SERVER. Let's try to get around this in our own ways, catch the file directory.

31 October 2018

Analysis of loaded parts of Php code with xhprof

After developing any tool in PHP, the question becomes how resourceful the created code is and what elements it still affects. Let's take a look at xhprof installation, configuration, and how to work with xhprof.

18 July 2018

Grouping conditions in an ORM Propel query (condition, combine)

Let's analyze the possibility of combining conditions in a query by groups in Propel. Consider an example of filtering by fields using ->condition() and ->combine().

14 June 2018

Authorization 1C on the site PHP_AUTH_USER on CentOS apache

Faced the problem of authorization 1s on the site. For some reason, the server did not accept the PHP_AUTH_USER and PHP_AUTH_PW parameters from it. Let's take a closer look at the solution and bypassing these parameters in $_SERVER .

Categories

  • Unix OS
  • Php
  • MySQL
  • JavaScript
  • Package Managers
  • Docker
  • Seo

Latest comments

Добрый день, Сергей. Я на более новых версиях блют...
root-i
23.02.23
Пробовал на transmart колонке. Ничего из перечисле...
Сергей
20.02.23
HenryMit, может быть
root-i
07.02.23
Неофрейдизм — это… Определение, принципы, представ...
HenryMit
07.02.23

I share information in which I needed help and spent a lot of time figuring it out. If the information helped at least one person, then this site was not created in vain.

Thank you for the continuation of the site:
Contacts

Telegram Viber Mail

Search for articles

  • Sign in
  • Create Account

Powered by chmod -R