How does the communication between classes work from client/user requests in MVC?

Asked

Viewed 449 times

1

Good afternoon, I am creating my MVC framework to better understand how this structure works and what may or may not be done within it. His structure is mounted like this:

inserir a descrição da imagem aqui

From what I understand so far of MVC I think it is a normal diagram, but who wants to comment or give suggestions are at ease.

Within the lib_controller i created a main class that makes an initial filter of the requests that are made before calling another controller. So, in the case of this url:

www.site.com.br/home

The class leading calls the class home which communicates with the classes in the lib_model and the classes of lib_view. Thus: inserir a descrição da imagem aqui

Classes of the Controller:

Main Class

class principal {

    function __construct(){

        if(isset($_GET['page'])){

            $class = $_GET['page'];
            require($class.".php");
            $classe = new $class();

        }

    }

}

Home class

class home {

    function __construct(){

        // peça os dados para o model!
        // peça para a view incluir os htmls!

    }

}

index php.

require("lib_controller/principal.php");
$control = new principal();

My question is this::

Is that wrong? Is it bad practice to create name classes in the controller that are called through the url? This could be a problem?

If yes in one of the questions... What is the best way to create this communication?

  • Class name in controller ? The controller contains actions of course, which you’re wondering about ?

  • @Edilson ... So... the main controler is a class called in the index. It checks the requests including via GET. In the case of the example GET is HOME so it calls the home class that in turn talks to the other classes in the model and view. That’s my idea, I don’t know if it’s right.

  • Look like you complicate, class is a set of methods (if it is still in failure, simply think of functions), in case the index what you refer to is probably a class method and not a class.

  • There can be no classes in the controller?

  • 2

    You misunderstood the concept. If you can find the mood, and there is still no answer, I’ll give you a simple example so that you understand more or less how it should be.

  • 5

    Just to make a point, something people confuse: 1. MVC is not technology per se is the way it creates/organizes 2. MVC does not depend on frameworks or object orientation 3. MVC came before the Web (add this to item 1)... In short, MVC is just one way to organize and can be totally optional, often being (many even) used needlessly, even more on simple web pages, where the method of organization could be something more simple and objective.

  • 5

    @Guilhermenascimento Even more in PHP :) I find it amazing how in Brazil people adopt OOP, MVC and templates in PHP without the slightest notion of what the language is. And the worst: there is a guy who has the courage to teach that "this is the right way" in college class, instead of teaching the student to go straight to the point and solve the problem objectively. There’s this snowball of people buying up the wrong idea and reselling, not knowing what they’re doing. Usually programming is a matter of reasoning, but in PHP it is a "profession of faith" :)

  • @Guilhermenascimento yes, I myself have observed some useful answers about MVC. But in this case, I want to better understand the concept in the communication part from the users requests.

  • 1

    @Andreicoelho see a very simple example of how to create something without classes and without MVC, however controlling such requests: https://answall.com/a/166110/3635

  • @Guilhermenascimento legal. Thanks. It’s just that I’m actually wanting to learn about MVC. Let me ask you... So MVC is another form of organization that separates the responsibilities of each part right? Isn’t there a specific way of communicating between the parties? That’s something I can create?

  • @Guilhermenascimento I know that in the example I gave putting products and home is kind of banal... rsrsrs..

  • 1

    As I said, MVC does not originate in the "webapps of life", it came well before, you can create MVC the way you want, with OOP or procedural, as long as you keep the responsibility of each in its proper place. MVC is not technology, you can use a framework like Laravel that "is supposed to be MVC" and end up not working MVC on it. MVC and the like are interesting when needed, or if the framework is well thought out and lightweight at the same time, in general most are not lean and usually contain a number of redundancies, of course to develop large systems are very advantageous.

  • 1

    https://answall.com/q/80060/3635, https://answall.com/q/21539/3635, https://answall.com/q/15916/3635, https://answall.com/q/22403/3635 e https://answall.com/a/55490/3635 (the latter is very vague, but the image is good, it is not defined that it should be so, but it is a good way of doing)

Show 8 more comments

1 answer

3


As others have said in the comments, the MVC It’s not technology, it’s just a way of organizing the project, separating into various logical parts that interact with each other forming the system. In the background nothing changes, only affects the way the data will transit from one side to another, creating a single entry point where all requests or data are captured and then processed appropriately and then returned to the user in information form.

Example using POO:

root
 \-model
   -BaseModel.php
 \-view
   -default.php
   -registar.php
 \-controller
   -DefaultController.php
 index.php

index php.:

<?php

DEFINE('DS', DIRECTORY_SEPARATOR);

spl_autoload_register(function($class){
    $dirs = array('model', 'view', 'controller');
    foreach($dirs as $dir){
        if(file_exists($dir . DS . $class . '.php')){
            require_once $dir . DS . $class . '.php';
        }
    }
});

$a = isset($_GET['a']) ? $_GET['a'] : '';
$m = isset($_GET['m']) ? $_GET['m'] : 'index';
$pedido = isset($_POST) ? $_POST : '';

switch($m){
    case 'qualquerOutro':
        $controller = new QualquerOutro(new QualquerModel);
        break;
    default:
        $controller = new DefaultController(new BaseModel);
}

$controller->load($a, $pedido);

Basemodel.php:

<?php
class BaseModel
{
    private $dados = [
        array(
            'id'=>2,
            'nome'=>'Fulano Jorge'
        ),
        array(
            'id'=>4,
            'nome'=>'Sicrano Antonio'
        )
    ];

    public function get($id=null)
    {
        if(isset($id)){
            foreach($this->dados as $dado){
                if($dado['id'] == $id){
                    return $dado;
                }
            }
        }
        return $this->dados;
    }

    public function set($dados)
    {
        foreach($this->dados as $k=>$dado){
            if($dado['id'] == $dados['id']){
                $this->dados[$k] = $dados;
                break;
            } else {
                array_push($this->dados, $dados);
                break;
            }
        }
        # para que se veja a mudança na matriz, já que os dados nao sao mantidos
        var_dump($this->dados);
    }
}

Defaultcontroller.php:

<?php
class DefaultController
{
    private $modelo = null;

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

    public function load($method = 'index', $pedido = array())
    {
        if(!method_exists($this, $method)){
            $method = 'index';
        }
        return $this->$method($pedido);
    }

    public function index()
    {
        $html = $this->modelo->get();
        include_once 'view' . DS . 'default.php';
    }

    public function registar($pedido){
        if($pedido):
            $this->modelo->set(['id'=>(int)$pedido['codigo'],'nome'=>$pedido['nome']]);
        endif;
        include_once 'view' . DS . 'registar.php';
    }
}

default.php:

<style type="text/css">
a {color:darkgray; text-decoration:none;}
a:hover {text-decoration:underline;}
ul {margin:1em 0; padding-left:.1em;}
ul li {list-style:none;}
table th {background-color:darkgray;}
table td {padding:.4em;}
</style>
<?php

echo <<<HTML
<h1>Pagina Inicial</h1>
<ul>
<li><a href="?a=registar">Cadastrar</a></li>
</ul>
<table>
<tr>
<th>Nome Completo</th>
<th>Acção</th>
</tr>
HTML;
foreach($html as $dado){
    $dd = json_encode($dado);
    print "<tr>";
    print "<td>" . $dado['nome'] . "</td><td><a href=\"#\" onclick='ver({$dd})'>visualizar</a></td>";
    print "</tr>";
}

?>
</table>
<script>
    function ver(obj){
        alert('ID: ' + obj.id + '\nNome: ' + obj.nome);
    }
</script>

register.php:

<style type="text/css">
a {color:darkgray; text-decoration:none;}
a:hover {text-decoration:underline;}
.field {margin:1em 0;}
</style>
<h1>Cadastrar Novo</h1>
<form method="POST" action="">
    <div class="field">
        <input type="text" name="codigo" placeholder="Codigo">
    </div>
    <div class="field">
        <input type="text" name="nome" placeholder="Digite o nome aqui">
    </div>
    <div class="botao">
        <input type="submit" value="cadastrar">
    </div>
</form>

This is what you see MVC, single entry, separate returns and treatment, and separate viewing. In fact, you can do it in a lot of ways, as long as you know what you’re doing, and what you intend to achieve by using it. The above example is something chaotic too (regrettably, yet it’s the best I could come up with on short notice), at least for me, but should be enough to pass the idea.

Procedural Example:

root
 \-minhas_paginas
   -default.php
   -registar.php
   -404.php
 fnc.php
 index.php

index php.:

<style type="text/css">
a {color:darkgray; text-decoration:none;}
a:hover {text-decoration:underline;}
.field {margin:1em 0;}
ul {margin:1em 0; padding-left:.1em;}
ul li {list-style:none;}
table th {background-color:darkgray;}
table td {padding:.4em;}
</style>
<?php


DEFINE('DS', DIRECTORY_SEPARATOR);
DEFINE('INC', 'minhas_paginas' . DS);
include_once 'fnc.php';

$a = isset($_GET['a']) ? $_GET['a'] : 'default';

if(in_array($a, ['default','registar','outroQualquer'])){
    if(file_exists(INC . $a . '.php')){
        include_once INC . $a . '.php';
    } else {
        include_once INC . '404.php';
    }
} else {
    include_once INC . '404.php';
}

fnc.php

<?php
$dados = [
    array(
        'id'=>2,
        'nome'=>'Fulano Jorge'
    ),
    array(
        'id'=>4,
        'nome'=>'Sicrano Antonio'
    )
];

function get($id=null)
{
    global $dados;
    if(isset($id)){
        foreach($dados as $dado){
            if($dado['id'] == $id){
                return $dado;
            }
        }
    }
    return $dados;
}

function set($dados)
{
    global $dados;
    foreach($this->dados as $k=>$dado){
        if($dado['id'] == $dados['id']){
            $this->dados[$k] = $dados;
            break;
        } else {
            array_push($dados, $dados);
            break;
        }
    }
    var_dump($dados);
}

default.php:

<?php
$html = get();

echo <<<HTML
<h1>Pagina Inicial</h1>
<ul>
<li><a href="?a=registar">Cadastrar</a></li>
</ul>
<table>
<tr>
<th>Nome Completo</th>
<th>Acção</th>
</tr>
HTML;
foreach($html as $dado){
    $dd = json_encode($dado);
    print "<tr>";
    print "<td>" . $dado['nome'] . "</td><td><a href=\"\" onclick='ver({$dd})'>visualizar</a></td>";
    print "</tr>";
}

?>
</table>
<script>
    function ver(obj){
        alert('ID: ' + obj.id + '\nNome: ' + obj.nome);
    }
</script>

register.php:

<?php
if(!empty($_POST)){
    set(['id'=>(int)$_POST['codigo'],'nome'=>$_POST['nome']]);
}
?>
<h1>Cadastrar Novo</h1>
<form method="POST" action="">
    <div class="field">
        <input type="text" name="codigo" placeholder="Codigo">
    </div>
    <div class="field">
        <input type="text" name="nome" placeholder="Digite o nome aqui">
    </div>
    <div class="botao">
        <input type="submit" value="cadastrar">
    </div>
</form>

404.php:

<h1>Pagina nao encontrada</h1>




Starting from the approach procedural, stays "probably" more evident, it is something that is done a lot and sometimes some do not even notice, when they begin to refactorate the code and so on.

MOdel: Modeling of data.

View: Presentation of information (data organized for a purpose...).

Controller: Controls the input data and what should be displayed. Basically the intermediary, since the information in the view depends on what is done in the controller.

The process basically consists of getting the information from somewhere (database for example), model this data, and pass it to the controller, and the controller present it in the view (There are cases where it may vary). The view must have as little logic as possible, because its purpose is to present the information to the user. The controller, on the other hand, is the one who has to decide what to display in the view from the model. Once again, the examples are not as I intended, but I believe they are sufficient to get the idea across.

NOTE: if there are still errors, or remain confused, correct when I have time.

  • I’ll take a closer look at the code later and evaluate it. But thanks for the example.

  • I like the way you set up the communication. I went deeper after the discussion above, and saw that frameworks use routes (Routes) to facilitate this communication of the controller the other parts of MVC. I am deepening... =) Thank you.

  • I even found this: https://answall.com/questions/135349/como-implementar-um-system-rotas-no-mvc

Browser other questions tagged

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