How to correctly divide php code into mvc

Asked

Viewed 501 times

1

I’m doing a website for a college class and I have to divide the code by following the MVC standard. Only I don’t know very well PHP, I’m learning during the discipline so I wanted to know how to correctly divide the code.

I wanted to create a class just for connection to the database, this class will be in the model. In the controller I wanted to put only the validations and etc, no messing with db by the controller. But I don’t know how to do this.

Code I wanted to learn 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");
    }
}
?>
  • I recommend you take a look at slim framework. With it you can create an application in MVC, and will save you time.

  • Can you give a summary of what MVC would be for you? I ask because it is 'work given', and the answers may not correspond with the theory you have learned... No controller queria colocar apenas as validações, this is an example - there are those who work with validations only in the Model, and those who work in the Controller

  • I took a look at the Slim framework, but the teacher wants us to put our hand in the same dough.

  • So I wanted to separate everything even in three folders. In the model I wanted to have the connection with the bank, the functions to insert, remove and edit. In the controller the issue of login, the registration that there in the case would call the insertion function defined in the model and etc. Things like this Papa Charlie, sorry if I did not explain very well.

1 answer

1


Let’s go in parts. Consider the following folder structure:

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

You will divide your code among the files in the hierarchy above. Then it gets:

Model

Connection Template.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;
        }
    }
?>

Model Usuariocrud.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']);
        }
    }
?>

Visao 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();
}
?>

User Controlcontrol.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';
     }
}
?>

That should help.

  • Thank you so much @Juven_v, that’s exactly what I wanted to understand!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.