How to correctly split php code in mvc

1

I'm making a site for a college course and I have to split the code following the MVC standard. But I do not know very well PHP, I'm learning during the course so I wanted to know how to properly divide the code.

I wanted to create a class just to connect to the database, this class will be in the template. In the controller wanted to put only the validations and etc, nothing to tinker in the db by the controller. But I do not know how to do it.

Code I wanted to learn how to divide correctly:

<?php


$email = $_POST['email'];
$entrar = $_POST['entrar'];
$senha = md5($_POST['senha']);
$connect = mysqli_connect('localhost','root','');
$db = mysqli_select_db($connect, 'meudb');
if (isset($entrar)) {        
  $verifica = mysqli_query($connect, "SELECT idcliente, nome, email, senha FROM clientes WHERE email = '$email' AND senha = '$senha'") or die("erro ao selecionar");
  $row = mysqli_fetch_assoc($verifica);
  $nome = $row['nome'];
    if (mysqli_num_rows($verifica)<=0){
      echo"<script language='javascript' type='text/javascript'>alert('Login e/ou senha incorretos');window.location.href='index.html';</script>";
      die();
    }else{
      if (!session_id())
                session_start();
            $_SESSION['logon'] = true;
            $_SESSION['user'] = $username;
            setcookie('usuario',$username,0,"/");
      header("Location:../View/adm.php");
    }
}
?>
    
asked by anonymous 16.12.2017 / 17:18

1 answer

1

Let's break it down. Consider the following folder structure:

/projeto (raiz)
    Modelo
        Conexao.php
        Usuario.php
        UsuarioCRUD.php
    Visao
        Login.php
    Controle
        Controle.php
        UsuarioControle.php

You will split your code between the files in the hierarchy above. Then it stays:

Template

Template \ Connection.php

<?php
class Conexao{
    private $usuario = 'root';
    private $senha = '';
    private $host = 'localhost';
    private $nomeBanco = 'meudb';
    private $conexao = null;

    public function __construct(){
        $this->conexao = mysqli_connect($this->host, $this->usuario,$this->senha);
        $db = mysqli_select_db($connect, $this->nomeBanco);
    }

    public function getConexao(){
        return $this->conexao;
    }
}
?>

Template \ User.php

<?php
    class Usuario{
        private nome = null;
        private $senha = null;
        private $email = null;

        public function __construct($nome = null, $senha = null, $email = null){
           $this->nome = nome;
           $this->senha = senha;
           $this->email = email;
        }

        public function getNome(){
            return $this->nome;
        }

        public function getSenha(){
            return $this->senha;
        }

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

Template \ UserCRUD.php

<?php
    require_once __DIR__ . DIRECTORY_SEPARATOR . 'Usuario.php';

    class UsuarioCRUD{
        private conexao = null;

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

        /*
          @return boolean | Usuario
        */
        public function usuarioExiste(Usuario $usuario){
            $verifica = mysqli_query($this->conexao, 
            "SELECT idcliente, nome, email, senha FROM clientes WHERE    email = '" 
            . $usuario->getEmail() ."' AND senha = '". $usuario->getSenha() . "'") or die("erro ao selecionar");

            $row = mysqli_fetch_assoc($verifica);

            if (mysqli_num_rows($verifica)<=0){
                 return false;
            }
            return new Usuario($row['nome'], $row['senha'], $row['email']);
        }
    }
?>

Vision \ Login.php

<html>
    <head>
    <head>
    <body>
       <form action="/Controle.php" method="post">
           <input name="email" type="text">
           <input name="senha" type="password">
           <input name="entrar" type="submit">
       <form>
    <body>
</html>

Control \ Control.php

<?php
session_start();
require_once __DIR__ . DIRECTORY_SEPARATOR . 'UsuarioControle.php';
if(isset($_POST['entrar'])){
    (new UsuarioControle())->logar($_POST);
}else if(isset($_GET['login'])){
    (new UsuarioControle())->login();
}
?>

Control \ User Control.php

<?php
require_once __DIR__ . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'Modelo' . DIRECTORY_SEPARATOR . 'UsuarioCRUD.php';
require_once __DIR__ . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'Modelo' . DIRECTORY_SEPARATOR . 'Usuario.php';
require_once __DIR__ . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'Modelo' . DIRECTORY_SEPARATOR . 'Conexao.php';

class UsuarioControle{
     private $usuarioCRUD = null;
     public function __construct(){
         $usuarioCRUD = new UsuarioCRUD((new Conexao())->getConexao());
     }

     //ao submeter o formulario
     public function _logar($dados){
         $usuario = $usuarioCRUD->usuarioExiste(new Usuario($dados['nome'], $dados['senha'], $dados['email']));

         if($status === false){
             echo 'Usuario inexistente';
         }else{
             if (!session_id())

                $_SESSION['logon'] = true;
                $_SESSION['user'] = $usuario->getNome();
                setcookie('usuario',$usuario->getNome(),0,"/");
                header("Location:../View/adm.php");
             }
         }
         die();
     }

     //ao chamar o formulario, algo como http://localhost/?login
     public function login(){
         require_once __DIR__ . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'Visao' . DIRECTORY_SEPARATOR . 'Login.php';
     }
}
?>

This should help.

    
17.12.2017 / 19:35