Am I using (learned) the MVC standard in the right way?

Asked

Viewed 324 times

0

/*Hello. A few years ago in college I took a pattern practice class with Php, and one of them was MVC. I learned from my teacher the MVC standard, but I don’t know until today the same was taught in the right way. Whenever I see projects with MVC standards are a little different from mine, in fact, the Controller class doesn’t seem to make much sense of what I’ve learned. I would like you to take a look at the way I program in MVC and say if I’m doing it the right way or if I could improve, because I’m really lost, especially in the Controller and Model part.

Na Model:

class ModelProduto{

private $id;
private $descricao;
private $valor;

public __construct(){
    // nada por aqui no momento...
}

protected function inserirProduto($produto){
    // realiza conexão com o banco
    // executa query no banco passando valores $produto->id, $produto->descricao, $produto->valor

    // retorna boolean se foi inserido com sucesso no banco ou nao
    return $resultado;
}

protected function buscarTodosProdutos(){
    // realiza conexão com o banco
    // traz os registros e armazenam em algum lugar, no caso, num array
    $produtos = new Array();
    foreach(resultado in lista){
        $produto = new Produto();
        $produto->id = resultado['id'];
        $produto->descricao = resultado['descricao'];
        $produto->valor = resultado['valor'];
        $produtos[] = $produto;
    }
    return $produtos;
}

// metodos Get e metodos Set em visibilidade public...
}

That done, in Controller which is where I have most doubt, I learned to structure it as follows:

class Produto extends ModelProduto{

// as vezes aqui um método ou outro (geralmente static) para montar um objeto ou fazer algo extra
// sempre tenho a função de montar objetos para ser usada mais tarde
public static criaObj($descricao, $valor){
    $produto = new Produto();
    $produto->setDescricao($descricao);
    $produto->setValor($valor);
    return $produto;
}

public function inserirProduto($produto){
    return parent::inserirProduto()
}

public function buscarTodosProdutos(){
    return parent::buscarTodosProdutos()
}
}

Once structured this MVC, in View, if I have a form to register this product, or display it, I do the following:

<html>
    <header></header>
    <body>
        <form method="POST" action="manipulaProduto.php">
            <!-- formulário aqui -->
        </form>
    </body>
</html>

Consequently I create another file in another folder called handles, where I check the form data and send it to controller, more or less like this:

if(isset($_POST['formularioEnviado'])){
    inserir();
}

function inserir(){
    // crio variaveis para pgar os $_POST e validar os campos, verificar se não existem nulos, poucos caracteres etc
    $validado = validarCampos();
    if($validado){
        // se passar pelas validações, chamo o inserir do Controller
        $inserido = inserirProduto();

        if($inserido){
            // envio alguma modal para a view informando que tudo foi validado com sucesso e demais eventos se necessário
            return $inserido;
        }
    }

    // envio alguma modal para a view informando erro no formulario se não entrar no if
    return $erros;

}

function validarCampos(){
    // valida os campos e retorna para a função acima
}

function inserirProduto(){
    // chamo o Controller e crio um objeto
    $produto = Produto->criaObj($_POST["descricao"], $_POST["valor"])
    $resposta = $produto->inserirProduto($produto);
    return $resposta;
}

This is the pattern I use in my project. It wasn’t all I learned in college, mostly I developed my own way of programming, but the question is the MVC standard. Sometimes I think this manipulationProduct.php plays the role that the Controller should play, because the controller does nothing more than transfer a function to the Model, which is almost useless in my view. Can you tell me how my structure is going, if something could be improved or if the MVC standard is really wrong? Remembering that this structure that I created here to present my problem is something extremely summarized and I didn’t get to run the codes, but this is the way I currently program. Thank you!

  • MVC is not OOP, it is not something that depends on how a program necessarily, but rather on how it organizes. So much so that it is possible to use MVC without OOP, in Web MVC it works different (note that MVC came well before web). One thing I find a big mistake (I could be mistaken) is that almost every popular frameworks or person using MVC seems to think that the Model should be exclusively an ORM. Now I’ll tell you what I always say about MVC, use if necessary, if you don’t have to use it, it has very simple site that use heavy frameworks, MVC and etc totally without...

  • ... need. MVC is an organization standard and has one goal, which is to make medium and large projects that can usually have a lot of people working, be able to guide themselves. You can use a popular MVC framework and still use it in a non-VMC way that works anyway. In short, do you need MVC? So use it. No need? So don’t use it. Do you want to understand what MVC is? Then go beyond code, you must understand necessity and communication. Any answer that states that this is correct or is an opinionated answer is already wrong ;)

1 answer

1

According to the MVC architecture, your model would be correct. You could search for design patterns to get other views about code organization and the project itself. Separate your model properties from your methods, connection services, side services, etc.

Your controller, he should not inherit from a model. They are different things. You will find many discussions about it. There is a recent here

Models must contain their business rule while Controllers must handle user requests and intermediar view and model.

What I didn’t understand was this:

Consequently I create another file in another folder called manipulate, where I check the data of the forms and send to controller

Why do you send your form to a place that validates and then sends it to the controller? And also: what is this place that validates?

Browser other questions tagged

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