Well, my question is very simple but a little hard to accept the solution, but anyway .. is the following, I have a 'mini-framework
', something to work on writing up of a single scheme, helps me a lot, accelerate work on some things, however, the question is even with the view, in a way, using a scheme of templates is very easy and also very interesting because when you have to change anything related to visualization
, the template changes only, but then, in time to render this template
, which is the best way? I'm currently working this way:
<?php
class View {
private $vars;
public function __get ( $var ) {
if ( isset( $this->vars [ $var ] ) ) {
return $this->vars[ $var ];
}
}
public function assign ( $var , $value ) {
$this->vars [ $var ] = $value;
}
public function show ( $template ) {
include_once sprintf ( "%s\Templates\%s" , __DIR__ , $template ) ;
}
}
It is not the complete code, I am building structures and reviewing the scheme yet, so I do the following ..
<?php
require_once 'MVC/Views/View.php';
$View = new View ( ) ;
$View->assign( 'title' , 'MVC, View Layer' ) ;
$View->show ( 'test.phtml' );
And the template
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8" />
<title><?php echo $this->title ?></title>
</head>
<body>
</body>
</html>
The output is correct, all working as expected
, but my question is: is this the best way to do? including the file and letting the play interprets the code written in .phtml
In many frameworks I saw this kind of statements:
public function show ( $template ) {
ob_start();
require sprintf ( "%s\Templates\%s" , __DIR__ , $template ) ;
return ob_get_flush();
}
Using the output buffer you can have the template evaluated to a string instead of directly sent in the output. This can come handy when you need to change headers after evaluating the template or to make post-processings.
Using require instead of include_once will allow you to render the same template more times (e.g. if you want to have some kind of templates composition) and to get an error if the template file is not found (include doesn't give an error in that situation).