Views with php transition with the controller

Asked

Viewed 158 times

1

I am a beginner in php, and so I have caught a lot. Also because I have used sublime text with apache and php installed separately (use Ubuntu with OS). Well my question regarding views and php is:
I don’t understand how you transition from controller to view. If I should mix php code with html tags, or if there is a way to include in the html file what is passed by a php code.

I know my doubt is very generic and initial, but if someone has a didactic example of how I do it, or if someone knows of some example project for me to see and understand also helps.

What else I have found on the net is concept and this I have already understood, now apply this in practice is another 500

  • It is not indicated to mix the view with php, to make the connection between both usually we use a template engine.

  • @Can you give me more information about this enginer template? As I explained in the question, I am very lost in this part, I am making mvc with 3 layers model (DAO, Value and Business), only now I stopped in the view question.

  • I posted information as answer I’m still learning all the features of Dwoo (a template engine)

  • Links where I am learning to work with dwoo: http://devzone.zend.com/1746/building-template-driven-web-applications-with-dwoo-part-1/ and http://devzone.zend.com/1760/building-template-driven-web-applications-withdwoo-part-2/

  • I appreciate your reply, but I still do not understand the transition, because I did not want to use template, I wanted to do on the arm even to know how it works in practice.

  • But "doing it on the arm" is by no means an option, because the middle field between the view and controller is not isolated to a junction where there is php code inside html, a proof would open a compiled template code (this is done automatically) you will see that there is PHP code inside HTML.

Show 1 more comment

2 answers

2

Luan,

You studying MVC without any right market framework? To be able to understand how works and improve your way of programming, when studying with PHP I made a project of a Phonebook using MVC without framework follows link on my github: https://github.com/jmfrolim/MVCSIMPLES

Example of code below:

<?php
/*
 * Essa classe é responsável por renderizar os arquivos HTML
 * 
 * @package Exemplo simples com MVC
 * @author João Manoel
 * @version 0.1.1
 * 
 * Diretório Pai - lib
 * Arquivo - View.php 
 */
 class View
 {
  /**
  * Armazena o conteúdo HTML
  * @var string
  */
private $st_contents;

/**
* Armazena o nome do arquivo de visualização
* @var string
*/
private $st_view;

 /**
 * Armazena os dados que devem ser mostrados ao reenderizar o 
 * arquivo de visualização
 * @var Array
 */
 private $v_params;

 /**
 * É possivel efetuar a parametrização do objeto ao instanciar o mesmo,
 * $st_view é o nome do arquivo de visualização a ser usado e 
 * $v_params são os dados que devem ser utilizados pela camada de    visualização
* 
* @param string $st_view
* @param Array $v_params
*/
function __construct($st_view = null, $v_params = null) 
{
    if($st_view != null)
        $this->setView($st_view);
    $this->v_params = $v_params;
}   

/**
* Define qual arquivo html deve ser renderizado
* @param string $st_view
* @throws Exception
*/
public function setView($st_view)
{
    if(file_exists($st_view))
        $this->st_view = $st_view;
    else
        throw new Exception("View File '$st_view' don't exists");       
}

/**
* Retorna o nome do arquivo que deve ser renderizado
* @return string 
*/
public function getView()
{
    return $this->st_view;
}

/**
* Define os dados que devem ser repassados à view
* @param Array $v_params
*/
public function setParams(Array $v_params)
{
    $this->v_params = $v_params; 
}

/**
* Retorna os dados que foram ser repassados ao arquivo de visualização
* @return Array
*/
public function getParams()
{
    return $this->v_params;
}

/**
* Retorna uma string contendo todo 
* o conteudo do arquivo de visualização
* 
* @return string
*/
public function getContents()
{
    ob_start();
    if(isset($this->st_view))
        require_once $this->st_view;
    $this->st_contents = ob_get_contents();
    ob_end_clean();
    return $this->st_contents;   
}

/**
* Imprime o arquivo de visualização 
*/
public function showContents()
{
    echo $this->getContents();
    exit;
}
}
 ?>
  • 2

    Thank you for improving the answer, which is more complete. The idea is that others in the future can learn from the answers. See you soon!

  • For nothing, I thank you for helping me find the best way!

  • I appreciate people, I understand things now, still a little confused but I get there. I did a half-dozen mvc at the time of displaying the collected data. But I will try to follow what you have been through, I will also download your example to better understand. Thanks for the strength.

  • @Luangabrieldacostarodrigue, it may be time for you to include your tests in your question so we can help on the way.

0

This is not good practice to mix the controller (system logic) with the view (visual part of the program that interacts with the user), to avoid the problems caused by this mixture and gain more operational security (the Web Designer and the Developer can work at the same time without the work of one interferes in the other) is used templates.

Examples of templates:

Smarty: Download link and documentation

Dwoo: Download link and documentation

Example of use (in the documentation more examples for other functionalities are provided):

<html>
  <head></head>
  <body>
    <blockquote>

    Palavra 1 <br/>
    Palavra 2 <br/>
    {$nome}      <br/>
    {$sobrenome}
    </blockquote>

  </body>
</html>

<?php
// auto-loader
include 'dwooAutoload.php';

// cria objeto Dwoo 
$dwoo = new Dwoo();

// le o templete acima definido
$tpl = new Dwoo_Template_File('tmpl/knock.tpl');

// valores dinamicos que serão injetados no template
$data = array();
$data['nome'] = 'Bill';
$data['sobrenome'] = 'Gates';

// injeta os valores e exibe a pagina, note que o nome do indices são identicos as 
//variaveis dentro do template, o dwoo irá fazer a injeção paseado nos nomes identicos.
$dwoo->output($tpl, $data);
?>

Browser other questions tagged

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