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.
Class name in controller ? The controller contains actions of course, which you’re wondering about ?
– Edilson
@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.
– Andrei Coelho
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.– Edilson
There can be no classes in the controller?
– Andrei Coelho
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.
– Edilson
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.
– Guilherme Nascimento
@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" :)
– Bacco
@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.
– Andrei Coelho
@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
– Guilherme Nascimento
@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?
– Andrei Coelho
@Guilhermenascimento I know that in the example I gave putting products and home is kind of banal... rsrsrs..
– Andrei Coelho
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.
– Guilherme Nascimento
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)
– Guilherme Nascimento