CRUD with MVC and DAO in PHP

Asked

Viewed 9,661 times

2

I’m starting with programming and I’m doing a CRUD with MVC and DAO. I would like to know if the form I am doing is correct, what I could improve and how I call the insertion method of Productocontroller in the form.

<?php

    class Database {

        private $host = "localhost";
        private $username = "root";
        private $password = "123456";
        private $database = "crud";


        public function conecta() 
        {
            $conexao = new mysqli($this->host, $this->username, $this->password, $this->database);
            return $conexao;        
        }
    }

<?php 

    class Produto {

        private $id;
        private $nome;
        private $descricao;
        private $preco;

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

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

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

        public function setNome($nome) {
            $this->nome = $nome;
        }

        public function getDescricao() {
            return $this->descricao;
        }

        public function setDescricao($descricao) {
            $this->descricao = $descricao;
        }

        public function getPreco() {
            return $this->preco;
        }

        public function setPreco($preco) {
            $this->preco = $preco;
        }

    }

<?php  

    class ProdutoDAO {

        function adiciona(Database $conexao, Produto $produto) {

            $query = "INSERT INTO produtos (nome, descricao, preco) VALUES ('{$produto->getNome()}', '{$produto->getDescricao()}', '{$produto->getPreco()}')";  
            mysqli_query($conexao->conecta(), $query);
        }

    }

<?php  

require_once ('../models/Produto.php');
require_once ('../models/ProdutoDAO.php');
require_once ('../config/Database.php');

class ProdutoController {

    public function insere() {
        $nome = $_POST['nome'];
        $descricao = $_POST['descricao'];
        $preco = $_POST['preco'];
        $conexao = new Database();
        $produto = new Produto();
        $produto->setNome($nome);
        $produto->setPreco($preco);
        $produto->setDescricao($descricao);
        $produtoDao = new ProdutoDao();
        $produtoDao->adiciona($conexao, $produto);
    }

}

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="../../public/css/bootstrap.min.css" rel="stylesheet">
<title>Adiciona Produto</title>
</head>
<body>
<div class="container">
<h3>Adicionar Produto</h3>
<form method="post" action="../../controllers/ProdutoController.php">
  <div class="form-group">
    <label>Nome</label>
    <input type="text" class="form-control" name="nome">
  </div>
  <div class="form-group">
    <label>Descrição</label>
    <input type="text" class="form-control" name="descricao">
  </div>
  <div class="form-group">
    <label>Preço</label>
    <input type="text" class="form-control" name="preco">
  </div>
  <button type="submit" class="btn btn-primary">Adicionar</button>
</form>
</div>
</body>
</html>
  • All that code is in one file ?

  • No. Each class has its own file. Where I open <? php is a file.

  • I edited to separate.

  • Marcelo you are not messing with MVC purely neh, is it a way you think it is MVC? (I judge this because this layer of model which is the relationship with bank) is almost good, with adjustment improvement and a lot. What I’m not getting is that you’re messing with files finished with .php and calling in the browser? Give an explanation!

  • I’m starting to see these patterns, and I don’t think they’re in the best shape, so I wanted tips on what to do. I don’t understand what you mean by calling in the browser? There is a form that I register for a product, that would be it. Only I don’t know how to call the insert method of Productocontroller.php So there is no php in the html form.

  • Yes Marcelo you’re calling it in action:../../controllers/ProdutoController.php! Nothing prevents you from working like this, is not wrong, does not mean that it is purely MVC, but, you have made your own division. Note filename .php we usually put everything into minuscules.

  • I get it, this is a detail. My problem is to make it work. As I said it is not perfect. How do I send the form data to the Productocontroller?

  • I did a roundup on what I think could be improved and how to utilize by <form/>. How are you using mysqli I did in procedural I find it simpler and easier to understand.

Show 3 more comments

2 answers

2


I’d change a few details:

database class

class Database 
{
    private $host = "localhost";
    private $username = "root";
    private $password = "123456";
    private $database = "crud";
    private $conexao = null; 

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

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

    private function conect() 
    {
        $this->conexao = mysqli_connect(
                  $this->host, 
                  $this->username, 
                  $this->password, 
                  $this->database);
    }
}

Product class

class ProdutoDAO 
{
    private $db;
    public function __construct(Database $db)
    {
        $this->db = $db;
    }

    public function add(Produto $produto) 
    {
        $nome = $produto->getNome();
        $descricao = $produto->getDescricao();
        $preco = $produto->getPreco();

        $query = "INSERT INTO produtos (nome, descricao, preco) VALUES(?,?,?)"; 
        $stmt = mysqli_prepare($this->db->getConection(), $query);
        mysqli_stmt_bind_param($stmt,'sss', $nome, $descricao, $preco);
        mysqli_stmt_execute($stmt); 
        mysqli_stmt_close($stmt);
    }

}

In addition to these changes, I think the bigger doubt would be how to perform this all by calling for a request from a <form />

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="../../public/css/bootstrap.min.css" rel="stylesheet">
<title>Adiciona Produto</title>
</head>
<body>
<div class="container">
<h3>Adicionar Produto</h3>
<form method="post" action="../../controllers/ProdutoController.php">
  <div class="form-group">
    <label>Nome</label>
    <input type="text" class="form-control" name="nome">
  </div>
  <div class="form-group">
    <label>Descrição</label>
    <input type="text" class="form-control" name="descricao">
  </div>
  <div class="form-group">
    <label>Preço</label>
    <input type="text" class="form-control" name="preco">
  </div>
  <button type="submit" class="btn btn-primary">Adicionar</button>
</form>
</div>
</body>
</html>

as in your <form /> the action flame ProdutoController.php, create a file with the same name and:

<?php  

require_once ('../models/Produto.php');
require_once ('../models/ProdutoDAO.php');
require_once ('../config/Database.php');

$db      = new Database();
$dao     = new ProdutoDao($db);

$produto = new Produto();
$produto->setNome($nome);
$produto->setPreco($preco);
$produto->setDescricao($descricao);

$dao->add($produto); // aqui grava o resultado enviado do form

redirect('Location:index.php');

  • So, this way you did leaving this Productocontroller.php file as a normal file, without being a class and not having a method worked, but wouldn’t it be right to call the Productocontroller.php input method? Because that way would no longer have a Product controller.

  • So, as I said I’m starting in programming and I’m trying to do a Crud on MVC and DAO. I don’t know much yet. I know that the MVC standard has the model, view and controller and that’s what I’m trying to do in this application. I created the model (Product.php), created the DAO (Product.php), created the controller (Product.php) and the view that is the registration form. I did a crud on the Laravel and tried to reproduce this structure without using it, but in Laravel it is used routes to call a controller method, in my case it would be the insert of Productocontroller.php.

  • But if I wanted to implement a simple CRUD could I not use MVC without using a framework or without having to build a framework for it? I’m making this application for study purposes understand.

0

Come on!

To begin with, I would like to highlight the true concept of MVC:

MVC is a software architecture standard that separates information (and its business rules) from the interface with which the user interacts.

That is, your code should in no way be defined in a giant block as if it were a structured programming(As in the C language, for example);

It’s even kind of complicated someone from here telling you how to "call" a method...in programming, we must follow all the steps to learn thinking big way!

I suggest you take a good look at the link I will send you to the end to learn the whole step by step and become a good programmer in the future!

I hope to answer your other questions in the future! ;)

https://www.webdevbr.com.br/mvc-e-php-entendendo-o-padrao-na-pratica-criando-um-framework-php

  • 1

    I don’t understand what you mean by giant block. They are separate files and not a single file.

  • 1

    I edited and separated the files pq is not a single file in my application but separate files. It has the name of the class and the php opening tag so I thought the people would draw.

  • 1

    It’s gotten a little better! Dude, there are several frameworks that you could use to help with development...this question that you asked, including already exists in the stackoverflow itself...but in the ". with"; http://stackoverflow.com/questions/17425765/php-mvc-call-controller-function-from-view

  • 1

    Yes, I did something in Laravel and I know that through routes I call the method. But I would like to do this crud in pure php, without framework.

Browser other questions tagged

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