MVC - Intermediate php file in View and Controller relationship

1

Hello everyone. I was reflecting on the existence of a structure relationship step in my project.

The organization of my project is as follows:

[1]Whenaccessingthepage,theusercanaccesseitherthenormaladdress(egcurso.php)orparameters(egcurso.php?curso=sistema_informacao).Inthecaseofaccessbynormaladdress,itisusuallyaccessedbythebuttonthathasthefileindex.php.Fromtheuseractionthecurso.phpcheckstoseeifanyparametershavebeenpassed,whichisusuallypassedviaajaxinstep[3].

[2]Assoonasthecurso.phpfilecompletestheparametercheck,itcallsthefileview_curso.php.Theaddresswillremainas.../curso.php

[3]Throughuseractions,javascriptdoesPOSTviaajaxtocurso.phpfileandoneoftheparametersthatissentiscalledopcao,socurso.phpknowswhichcontrollerfunctionshouldcall,step[4].

functionpesquisar(){varcurso=documento.getElementById("id_curso").value;
    $.ajax({
        type: "POST",
        url: "curso.php",
        data: {
            "curso": curso,
            'opcao': 'pesquisar_disciplinas'
        }
    });
}

[4] The controller checks the action and if the parameters are correct it calls the class that will execute that action.

[5] In this example, the action being a select, then the controller calls the model_curso.php .

[6] The model_curso.php returns the result for the controller.

[7] The controller checks, and in this example it calls the file view_painel_curso.php with the results of model_curso.php .

The question I have is whether there really is a need for the curso.php file to exist.

Basically, the file curso.php is an intermediary of the view and the controller, and has as a function to make a filter of what is being requested by the view and to pass to the controller that then dictates who will execute.

Is there any variation of the MVC that uses this architecture that I'm using or can we say that it still is the MVC? Do you use some similar structure?

course.php

<?php

# Importar bibliotecas e classes
require_once "../require.php";

# Importar controlador
require_once "./controllers.php";

// mostrar exceções de banco de dados
$APP->getDBLink()->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION); 

# exigir que usuário esteja logado
$APP->requireLoggedUser(true);

# Inicializar o objeto controlador
$Ctrl = new \curso\Controller($APP);

# método da requisição
$reqmethod = $_SERVER['REQUEST_METHOD'];

if( $reqmethod == "POST" ) {
    $opcao          = filter_input(INPUT_POST, "opcao");

    // salvar disciplina
    if ($opcao == "salvar_curso"){
        $Ctrl->salvarCurso(['POST' => $_POST]);
   // pesquisar curso
    } elseif($opcao == "pesquisar_disciplinas"){
        $Ctrl->getDisciplinas($_POST);

    }
} else {

    $curso = filter_input(INPUT_GET, "curso");
    $disciplina = filter_input(INPUT_GET, "disciplina");

    if(isset($curso)) {

        $APP->requireLoggedUser(true);

        # Define qual parte do controlador vai usar
        $content = function() use($Ctrl) {
            // 
            $Ctrl->pesquisar(['GET' => $_GET ]);
        };
    } else {
        $content = function() use($Ctrl){
            $Ctrl->indexAction('view_curso');
        };
    }

    # qual template HTML
    $qual_template = 'basico2';

    # título da página
    $title = 'Cursos Faculdade';

    $options['css']['files'][] = '<link href="static/estilos.css" rel="stylesheet" type="text/css">';
    $options['js_files'][] = '<script src="./static/assets/moment/moment.js"></script>';
    $options['js_files'][] = '<script src="./static/assets/moment/moment-with-locales.js"></script>';
    $options['js_files'][] = '<script type="text/javascript" src="static/curso.js"></script>';

    $options['favicon'] = '<link  id="favicon" rel="shortcut icon" href="/static/imgs/icone.png" type="text/css" />';

    # chamar o template 
    $APP->printTemplate( $qual_template, $title, $content, $options );
}
?>
    
asked by anonymous 05.01.2019 / 16:36

1 answer

2
  

I'll assume your real problem is about structuring your code in order to follow the MVC pattern. For questions like: "- Do you use any similar structure?" end up not being a real problem, as defined in the central of community help .

Let's say: you're running away from the theory of the MVC pattern the moment you intermedia the actions of each of your sectors (Model, View, and Controller).

See that your curso.php file is mixing the MVC service in several sectors: Starting the application, calling the controller, calling the model, and rendering. See:

# Importar bibliotecas e classes
require_once "../require.php";

# Importar controlador
require_once "./controllers.php";

// ...

# Inicializar o objeto controlador
$Ctrl = new \curso\Controller($APP);

# método da requisição
$reqmethod = $_SERVER['REQUEST_METHOD'];

// ...

# chamar o template 
$APP->printTemplate( $qual_template, $title, $content, $options );

When we have developed an application based on the MVC pattern, we have created the known bootstrap calls "the right controller, according to the user's request.

As you can see, you are calling the driver / method in the curso.php file, which causes that bootstrap to be this file.

As a workaround, I can suggest the following:

Develop your bootstrap in a way that is dynamic. The controller / method can be passed via parameter (eg, http://meu.site.com/index.php?controlador=cursos&metodo=ver ) or via friendly URL (eg: http://meu.site.com/cursos/ver - requires Apache specific configuration / .htaccess ). >

In most MVC diagrams this is omitted, being considered as part of controller . But it is not! It is responsible for calling the controller and the right method, as already mentioned.

Another thing you can consider is to use an AutoLoader to load your classes. I recommend the PSR-4: Autoloader - PHP-FIG .

Since it is not the one asked, I will not go into more detail about the MVC pattern (such as structuring, what to develop in each place, and so on). I made a point of explaining this part because it refers to the context of the question. However, I suggest that you deepen your study / development on what I have given you.

    
05.01.2019 / 17:52