How does communication between classes work from client / user requests in MVC? [closed]

1

Good afternoon, I'm creating my MVC framework to better understand how this structure works and what can or can not be done inside it. His structure is set up like this:

FromwhatIunderstandsofarfromMVCIthinkit'sanormaldiagram,butanyonewhowantstocommentorgivesuggestionsisfree.

Withinlib_controllerIcreatedamainclassthatdoesaninitialfilterofrequeststhataremadebeforecallinganothercontroller.Sointhecaseofthisurl:

  

www.site.com.br/home

Themainclassclasscallsthehomeclassthatcommunicateswithclassesinlib_modelandlib_viewclasses.Likethis:

ControllerClasses:

MainClass

classprincipal{function__construct(){if(isset($_GET['page'])){$class=$_GET['page'];require($class.".php");
            $classe = new $class();

        }

    }

}

Class Home

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:

Is this wrong? Is it a bad practice for you to create name of classes in the controller that are called through the url? Can this be a problem?

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

    
asked by anonymous 15.04.2017 / 22:26

1 answer

3

As others have already said in the comments, MVC is not technology, it's just a way of organizing the project, separating into several logical parts that interact with each other to form the system. In the background nothing changes, it only affects how the data will transit from one place to another, creating a single point of entry where all requisitions or data are captured and then processed properly and then returned to the user in the form of information.

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>

registar.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>

What you see there is MVC , single entry, separate returns and treatment, and side view. In fact, you can do this in a variety of ways, as long as you know what you're doing, and what you want to achieve by using that. The above example is somewhat chaotic too (sadly, it's still the best I could manage in a short time) , at least for me, but it should be enough to get the idea across.

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>

registar.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>


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

M odel: Data modeling.

V iew: Presentation of information (data organized with a purpose ...) .

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

The process basically consists of picking up the information from some place (database for example) , modeling this data, and passing them to the controller, and the controller presents them in the < in> (There are cases where it may vary) . The view should have the least possible logic, because the purpose of it is to present the information to the user. The controller on the other hand, is who should decide what should be presented in the view from the model. Once again, the examples are not what they intended, but I think they are enough to get the idea across.

  

NOTE: If there are still errors, or remain confused, correct when you have time.

    
17.04.2017 / 00:11