mvc

PHP MVC Step by Step Live project Example

Spread the love

PHP MVC Learn For Beginners

This is a PHP MVC step-by-step tutorial where you will learn to develop a PHP application using the MVC pattern. The tutorial is divided into 7 different parts (steps) in order to achieve a fully functional PHP CRUD application based on the Model-View-Controller arch pattern.

  • Table of Contents
    • [Why MVC?] (# Github)
    • [Introduction to Model View Controller] (# ignore-whitespace)
    • [Advantages] (# ignore-whitespace)
    • [What you should know about MVC] (# adjust-tab-space)
    • [Commit History by Author] (# commit-history-by-author)
    • [Before getting started] (# cloning-a-repository)
    • [Our MVC sample application] (# cloning-a-repository)
    • [Technologies used] (# technologies-used)
    • [Functionalities] (# functionalities)
    • [Pre-requisites] (# cloning-a-repository)
    • [Development environment and setting up the databse] (# cloning-a-repository)
    • [Tutorial] (# cloning-a-repository)
    • [First step: creating the basic structure] (# cloning-a-repository)
    • [Second step: adding multiple views to our application] (# cloning-a-repository)
    • [Third step: implementing a generic Front-Controller]
    • [Fourth step: adding complexity to our application] (# cloning-a-repository)
    • [Fifth step: Powerfull controllers and models using inheritance] (# cloning-a-repository)
    • [Sixth step: Advanced views using templates] (# cloning-a-repository)
    • [Seventh step: 3 layer architecture] (# cloning-a-repository)
    • [Eighth step: Handling AJAX requests] (# cloning-a-repository)
    • [Contributing] (# contributing)

employee

  • Technologies used
    • PHP
    • PDO
    • MySQL
    • jQuery
    • Bootstrap v4

Functionalities

  • Registration and Login.
  • Post ads.
  • Profile: user data, published announcements, mark announcement as sold, delete announcements.
  • Mark as favorites.
  • Modify user data.
  • Show favorites in profile.
  • Image upload PHP.
  • (ALL) Delete favorites from profile.
  • (ALL) Responsive navbar.

Follow Few Steps

Step1:- Create a database and name it MVC Now create a table in this database Name it employees Give the SQL of the table I have given here Copy and paste it into your database.

CREATE TABLE Employees (
id INT(6) AUTO_INCREMENT PRIMARY KEY,
Name VARCHAR(30) NOT NULL,
Surname VARCHAR(80) NOT NULL,
email VARCHAR(50),
phone VARCHAR(20)
)

Step2:- Create MVC Folder

Step3:- Create the Config folder in the MVC folder

Step4:- Create two files in the config folder, one database.php and the other global.php

database.php

<?php

define("DB_DRIVER", "mysql");
define("DB_HOST", "localhost");
define("DB_USER", "root");
define("DB_PASS", "");
define("DB_DATABASE", "mvc");
define("DB_CHARSET", "utf8");

/*
return array(
    "driver"    =>"mysql",
    "host"      =>"localhost",
    "user"      =>"root",
    "pass"      =>"",
    "database"  =>"mvc1",
    "charset"   =>"utf8"
);
*/

?>

global.php

<?php
define("CONTROLLER_DEFECTO", "Employees");
define("DEFECT_ACTION", "index");
?>

Step5:- Create a controller folder in the MVC folder again

Step6:- Create a file in the controller folder, give the name employeesController.php

employeesController.php

<?php
class EmployeesController{

    private $conectar;
    private $Connection;

    public function __construct() {
		require_once  __DIR__ . "/../core/Conectar.php";
        require_once  __DIR__ . "/../model/employee.php";
        
        $this->conectar=new Conectar();
        $this->Connection=$this->conectar->Connection();

    }

   /**
    * Ejecuta la acción correspondiente.
    *
    */
    public function run($accion){
        switch($accion)
        { 
            case "index" :
                $this->index();
                break;
            case "alta" :
                $this->crear();
                break;
            case "detalle" :
                $this->detalle();
                break;
            case "actualizar" :
                $this->actualizar();
                break;
            default:
                $this->index();
                break;
        }
    }
    
   /**
    * Loads the employees home page with the list of
    * employees getting from the model.
    *
    */ 
    public function index(){
        
        //We create the employee object
        $employee=new Employee($this->Connection);
        
        //We get all the employees
        $employees=$employee->getAll();
       
        //We load the index view and pass values to it
        $this->view("index",array(
            "employees"=>$employees,
            "titulo" => "PHP MVC"
        ));
    }

    /**
    * Loads the employees home page with the list of
     * employees getting from the model.
    *
    */ 
    public function detalle(){
        
        //We load the model
        $modelo = new Employee($this->Connection);
        //We recover the employee from the BBDD
        $employee = $modelo->getById($_GET["id"]);
        //We load the detail view and pass values to it
        $this->view("detalle",array(
            "employee"=>$employee,
            "titulo" => "Detalle Employee"
        ));
    }
    
   /**
    * Create a new employee from the POST parameters
     * and reload the index.php.
    *
    */
    public function crear(){
        if(isset($_POST["Name"])){
            
            //Creamos un usuario
            $employee=new Employee($this->Connection);
            $employee->setName($_POST["Name"]);
            $employee->setSurname($_POST["Surname"]);
            $employee->setEmail($_POST["email"]);
            $employee->setphone($_POST["phone"]);
            $save=$employee->save();
        }
        header('Location: index.php');
    }

   /**
    * Update employee from POST parameters
     * and reload the index.php.
    *
    */
    public function actualizar(){
        if(isset($_POST["id"])){
            
            //We create a user
            $employee=new Employee($this->Connection);
            $employee->setId($_POST["id"]);
            $employee->setName($_POST["Name"]);
            $employee->setSurname($_POST["Surname"]);
            $employee->setEmail($_POST["email"]);
            $employee->setphone($_POST["phone"]);
            $save=$employee->update();
        }
        header('Location: index.php');
    }
    
    
   /**
    * Create the view that we pass to it with the indicated data.
    *
    */
    public function view($vista,$datos){
        $data = $datos;  
        require_once  __DIR__ . "/../view/" . $vista . "View.php";

    }

}
?>

Step7:- Create a core folder in the MVC folder again

Step8:- Create a file in the code folder, give the name Conectar.php

Conectar.php

<?php
class Conectar{
    private $driver;
    private $host, $user, $pass, $database, $charset;
  
    public function __construct() {
        $db_cfg = require_once 'config/database.php';
        $this->driver=DB_DRIVER;
        $this->host=DB_HOST;
        $this->user=DB_USER;
        $this->pass=DB_PASS;
        $this->database=DB_DATABASE;
        $this->charset=DB_CHARSET;
    }
    
    public function Connection(){

        $bbdd = $this->driver .':host='. $this->host .  ';dbname=' . $this->database . ';charset=' . $this->charset;

        //$bbdd = ' mysql:host=localhost;dbname=mvc1;charset=utf8';
        try {
            $connection = new PDO($bbdd, $this->user, $this->pass);
            $connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            return $connection;
        } catch (PDOException $e) {
            //We throw the exception
            throw new Exception('Problem establishing the connection.');
        }
    }

}
?>

Step9:- Create a model folder in the MVC folder again

Step10:- Create a file in the model folder, give the name employee.php

employee.php

<?php
class Employee {
    private $table = "employees";
    private $Connection;

    private $id;
    private $Name;
    private $Surname;
    private $email;
    private $phone;

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

    public function getId() {
        return $this->id;
    }

    public function setId($id) {
        $this->id = $id;
    }
    
    public function getName() {
        return $this->Name;
    }

    public function setName($Name) {
        $this->Name = $Name;
    }

    public function getSurname() {
        return $this->Surname;
    }

    public function setSurname($Surname) {
        $this->Surname = $Surname;
    }

    public function getEmail() {
        return $this->email;
    }

    public function setEmail($email) {
        $this->email = $email;
    }

    public function getphone() {
        return $this->phone;
    }

    public function setphone($phone) {
        $this->phone = $phone;
    }

    public function save(){

        $consultation = $this->Connection->prepare("INSERT INTO " . $this->table . " (Name,Surname,email,phone)
                                        VALUES (:Name,:Surname,:email,:phone)");
        $result = $consultation->execute(array(
            "Name" => $this->Name,
            "Surname" => $this->Surname,
            "email" => $this->email,
            "phone" => $this->phone
        ));
        $this->Connection = null;

        return $result;
    }

    public function update(){

        $consultation = $this->Connection->prepare("
            UPDATE " . $this->table . " 
            SET 
                Name = :Name,
                Surname = :Surname, 
                email = :email,
                phone = :phone
            WHERE id = :id 
        ");

        $resultado = $consultation->execute(array(
            "id" => $this->id,
            "Name" => $this->Name,
            "Surname" => $this->Surname,
            "email" => $this->email,
            "phone" => $this->phone
        ));
        $this->Connection = null;

        return $resultado;
    }
        
    
    public function getAll(){

        $consultation = $this->Connection->prepare("SELECT id,Name,Surname,email,phone FROM " . $this->table);
        $consultation->execute();
        /* Fetch all of the remaining rows in the result set */
        $resultados = $consultation->fetchAll();
        $this->Connection = null; //cierre de conexión
        return $resultados;

    }
    
    
    public function getById($id){
        $consultation = $this->Connection->prepare("SELECT id,Name,Surname,email,phone 
                                                FROM " . $this->table . "  WHERE id = :id");
        $consultation->execute(array(
            "id" => $id
        ));
        /*Fetch all of the remaining rows in the result set*/
        $resultado = $consultation->fetchObject();
        $this->Connection = null; //connection closure
        return $resultado;
    }
    
    public function getBy($column,$value){
        $consultation = $this->Connection->prepare("SELECT id,Name,Surname,email,phone 
                                                FROM " . $this->table . " WHERE :column = :value");
        $consultation->execute(array(
            "column" => $column,
            "value" => $value
        ));
        $resultados = $consultation->fetchAll();
        $this->Connection = null; //connection closure
        return $resultados;
    }
    
    public function deleteById($id){
        try {
            $consultation = $this->Connection->prepare("DELETE FROM " . $this->table . " WHERE id = :id");
            $consultation->execute(array(
                "id" => $id
            ));
            $Connection = null;
        } catch (Exception $e) {
            echo 'Failed DELETE (deleteById): ' . $e->getMessage();
            return -1;
        }
    }
    
    public function deleteBy($column,$value){
        try {
            $consultation = $this->Connection->prepare("DELETE FROM " . $this->table . " WHERE :column = :value");
            $consultation->execute(array(
                "column" => $value,
                "value" => $value,
            ));
            $Connection = null;
        } catch (Exception $e) {
            echo 'Failed DELETE (deleteBy): ' . $e->getMessage();
            return -1;
        }
    }
    
}
?>

Step11:- Create a view folder in the MVC folder again

Step12:- Create two files in the config folder, one detalleView.php and the other indexView.php

detalleView.php

<!DOCTYPE HTML>
<html lang="es">
    <head>
        <meta charset="utf-8"/>
        <title>Example PHP+PDO+POO+MVC</title>
        <link href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
        <script type="text/javascript" src="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
        <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
        <style>
            input{
                margin-top:5px;
                margin-bottom:5px;
            }
            .right{
                float:right;
            }
        </style>
    </head>
    <body>
        <div class="col-lg-5 mr-auto">
            <form action="index.php?controller=employees&action=actualizar" method="post">
                <h3>User detail</h3>
                <hr/>
                <input type="hidden" name="id" value="<?php echo $datos["employee"]->id ?>"/>
                Name: <input type="text" name="Name" value="<?php echo $datos["employee"]->Name ?>" class="form-control"/>
                Surname: <input type="text" name="Surname" value="<?php echo $datos['employee']->Surname ?>" class="form-control"/>
                Email: <input type="text" name="email" value="<?php echo $datos['employee']->email ?>" class="form-control"/>
                phone: <input type="text" name="phone" value="<?php echo$datos['employee']->phone ?>" class="form-control"/>
                <input type="submit" value="Send" class="btn btn-success"/>
            </form>
            <a href="index.php" class="btn btn-info">Return</a>
        </div>
       
    </body>
</html>

indexView.php

<!DOCTYPE HTML>
<html lang="es">
    <head>
        <meta charset="utf-8"/>
        <title>Example PHP+PDO+POO+MVC</title>
        <link href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
        <script type="text/javascript" src="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
        <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
        <style>
            input{
                margin-top:5px;
                margin-bottom:5px;
            }
            .right{
                float:right;
            }
        </style>
    </head>
    <body>
        <form action="index.php?controller=employees&action=alta" method="post" class="col-lg-5">
            <h3>Add user</h3>
            <hr/>
            Name: <input type="text" name="Name" class="form-control"/>
            Surname: <input type="text" name="Surname" class="form-control"/>
            Email: <input type="text" name="email" class="form-control"/>
            phone: <input type="text" name="phone" class="form-control"/>
            <input type="submit" value="Send" class="btn btn-success"/>
        </form>
        
        <div class="col-lg-7">
            <h3>Users</h3>
            <hr/>
        </div>
        <section class="col-lg-7 usuario" style="height:400px;overflow-y:scroll;">
            <?php foreach($datos["employees"] as $employee) {?>
                <?php echo $employee["id"]; ?> -
                <?php echo $employee["Name"]; ?> -
                <?php echo $employee["email"]; ?> -
                <?php echo $employee["phone"]; ?>
                <div class="right">
                    <a href="index.php?controller=employees&action=detalle&id=<?php echo $employee['id']; ?>" class="btn btn-info">Detalles</a>
                </div>
                <hr/>
            <?php } ?>
        </section>
		
        
    </body>
</html>

Step13:-Now create an index.php file in the mvc Folder

index.php

<?php
//Global setting
require_once 'config/global.php';

//We load the controller and execute the action
if(isset($_GET["controller"])){
    // We load the instance of the corresponding controller
    $controllerObj=cargarControlador($_GET["controller"]);
    //We launch the action
    launchAction($controllerObj);
}else{
    // We load the default controller instance
    $controllerObj=cargarControlador(CONTROLLER_DEFECTO);
    // We launch the action
    launchAction($controllerObj);
}


function cargarControlador($controller){

    switch ($controller) {
        case 'employees':
            $strFileController='controller/employeesController.php';
            require_once $strFileController;
            $controllerObj=new employeesController();
            break;
        
        default:
            $strFileController='controller/employeesController.php';
            require_once $strFileController;
            $controllerObj=new EmployeesController();
            break; 
    }
    return $controllerObj;
}

function launchAction($controllerObj){
    if(isset($_GET["action"])){
        $controllerObj->run($_GET["action"]);
    }else{
        $controllerObj->run(DEFECT_ACTION);
    }
}

/*
function cargarControlador($controller){
	// We create the Name of the controller: e.j. userController
    $controlador=ucwords($controller).'Controller';
    // We create the Name of the controller file: e.j. controller / userController.php
    $strFileController='controller/'.$controlador.'.php';
    //If there is no controller with that, we load the one defined by default.
    if(!is_file($strFileController)){
        $strFileController='controller/'.ucwords(CONTROLLER_DEFECTO).'Controller.php';   
    }
    //We load the file where the controller is defined:
    require_once $strFileController;
    //We create the object
    $controllerObj=new $controlador();
    return $controllerObj;
}
*/


?>

Output:-

MVC Output
Enter Value and click send Button
This show Your data
Your Database

PHP MVC Live Project Demo Download here


Spread the love

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *