Implementing the View in MVC or MVP (in PHP) - php

I've experienced first hand the extent of the horror and foot-shooting that the ugliness of PHP can cause. I'm onto my next project (you may be wondering why I'm not just switching languages but that's not why I'm here) and I've decided to try doing it right, or at least better, this time.
I've got some models defined, and I've started on a main controller. I'm at a fork in my decisions about how to implement the view. So far, the main controller can be given lists of display functions to call, and then it can spew out the whole page with one call. It looks like:
function Parse_Body()
{
foreach ($this->body_calls as $command)
{
$call = $command['call'];
if (isset($command['args'])) $call($command['args']);
else $call();
}
}
My dilemma is this:
Would it be better to have all of my display functions return the HTML they generate, so that the main controller can just echo $page; or should the display files use raw HTML outside of PHP, which gets output as soon as it's read?
With the former, the main app controller can precisely control when things get output, without just relinquishing complete control to the whim of the displays. Not to mention, all those lists of display functions to call (above) can't really be executed from a display file unless they got passed along. With the latter method, I get the benefit of doing HTML in actual HTML, instead of doing huge PHP string blocks. Plus I can just include the file to run it, instead of calling a function. So I guess with that method, a file is like a function.
Any input or advice please?

Would it be better to have all of my
display functions return the HTML they
generate, so that the main controller
can just echo $page; or should the
display files use raw HTML outside of
PHP, which gets output as soon as it's
read?
One of the advantages of php is that the processing is similar to the output:
So:
<h1> <?= $myHeading; ?> </h1>
Is more clear than:
echo "<h1>$myHeading</h1>";
An even more than:
echo heading1($myHeading); //heading1() being an hypothethical user defined function.
Based on that I consider that it is better to in the view to have HTML and and just print the appropriate dynamic fields using php.
In order to get finner control over the output you can use: ob_start as gurunu recommended.
You could of course use any of the several php MVC frameworks out there.
My prefered one, now is: Solarphp
but Zend Framework and Cakephp could help you too.
And finally if you don't want to use any framework
You could still use a pretty slim templating engine: phpSavant.
That will save you a few headaches in the development of your view.
th

You can get the benefit of both, obtaining a string of HTML while also embedding HTML within PHP code, by using the output control functions:
From the PHP manual # http://www.php.net/manual/en/ref.outcontrol.php:
<?php
function callback($buffer)
{
// replace all the apples with oranges
return (str_replace("apples", "oranges", $buffer));
}
ob_start("callback");
?>
<html>
<body>
<p>It's like comparing apples to oranges.</p>
</body>
</html>
<?php
ob_end_flush();
?>

First buffer everything. then replace tags using a parser at end of script.
<?php
$page_buffer = '';
function p($s){
global $page_buffer;
$page_buffer .= $s;
}
$page_buffer = str_replace(
array('<$content$>','<$title$>'),
array($pagecontent,$pagetitle),
$page_buffer);
echo $page_buffer;
?>
Samstyle PHP Framework implements output buffering and View model this way
And did I mention about benefits of buffering your output in a variable before "echo-ing"? http://thephpcode.blogspot.com/2009/02/php-output-buffering.html

Related

Separating php from html

I am building a website using php. I would want to separate the php from the html. Smarty engine, I guess does that, but right now its too complicated for me. Looking for a quick fix and easy to learn solution, one which is an accepted standard as well. Anyone helping please.
Consider frameworks or choose a template engine
Use a framework. Depending on your project, either a micro framework like Slim or something more complete like Laravel.
What I sometimes do when writing complex systems with quite much php code is separating it the following way (don't know your exact project, but it might work for you):
You create a php file with all the functions and variables you need. Then, you load every wepgage through the index.php file using .htaccess (so that a user actually always loads the index.php with a query string). Now, you can load the html page using file_get_contents (or similar) into a variable (I call this $body now); this variable can be modified using preg_replace.
An example: In the html file, you write {title} instead of <title>Sometext</title>
The replacement replaces {title} with the code you actually need:
$body = str_replace('{title}', $title, $body);
When all replacements are done, simply echo $body...
Just declare a lot of variables and use them in the template:
In your application:
function renderUserInformation($user)
{
$userName = $user->userName;
$userFullName = $user->fullName;
$userAge = $user->age;
include 'user.tpl.php';
}
In user.tpl.php:
User name: <?=$username?><br>
Full name: <?=userFullName?><br>
Age: <?=$userAge?>
By putting it in a function, you can limit the scope of the variables, so you won't pollute your global scope and/or accidentally overwrite existing variables.
This way, you can just 'prepare' the information needed to display and in a separate php file, all you need to do is output those variables.
Of course, if you must, you can still add more complex PHP code to the template, but try to do it as little as possible.
In the future, you might move this 'render' function to a separate class. In a way, this class is a view (a User View, in this case), and it is one step in creating a MVC structure. (But don't worry about that for now.)
Looking for a quick fix and easy to learn solution
METHOD 1 (the laziest; yet you preserve highlighting on editors like notepad++)
<?php
// my php
echo "foo";
$a = 4;
// now close the php tag -temporary-
// to render some html in the laziest of ways
?>
<!-- my html -->
<div></div>
<?php
// continue my php code
METHOD 2 (more organized; use template files, after you passed some values on it)
<?php
// my php
$var1 = "foo";
$title = "bar";
$v = array("var1"=>"foo","title"=>"bar"); // preferrable
include("template.php");
?>
template.php
<?php
// $var1, $var2 are known, also the array.
?>
<div>
<span> <?php echo $v["title"]; ?> </span>
</div>
Personally, i prefer method 2 and im using it in my own CMS which uses lots and lots of templates and arrays of data.
Another solution is of course advanced template engines like Smarty, PHPTemplate and the likes. You need a lot of time to learn them though and personally i dont like their approach (new language style)
function renderUserInformation($user)
{
$userName = $user->userName;
$userFullName = $user->fullName;
$userAge = $user->age;
include 'user.tpl.php';
}

Are there any limitations on where PHP code can go inside a file?

Can you put PHP anywhere in a file? Inside tags and quotes? For example, is something like this guaranteed to work (even though it isn't always recognized by an IDE's syntax highlighter):
<tr><tbody <?php if(!$row) echo "style='display: none;'"; ?>>
<!-- stuff that we only want to show if $row exists -->
</tbody></tr>
Or for example:
<a href="http://www.google.com/search?q=<?= echo $searchTerm; ?>"</a>
I know I can test this sort of thing on my machine, but I'm wondering if it is guaranteed/defined behavior and if there are any edge cases that don't work that I've missed.
Also, is there good reason not to do this? Is it dangerous because the next person looking at the code might miss it? Should I put a comment in? Does having to add a comment defeat the purpose of this method - succinctness?
Yes you can put the php tags anywhere in the page (html) there is no stopping you on that.
If we go under the hood, your web server sends the code to the php interpreter via a handler and merges the output with your static html file and sends the merged file as the response.
To add to my answer, developers usually go for MVC based frameworks so that the php code inside html page is restricted to only printing the variables and the business logic is performed in the controllers. I personally prefer CakePHP. Apart from that you might not want to put code that manipulates session or performs redirection between html tags else you will recieve the headers already set error as you have already printed certain html code before modifying the headers.

PHP: Using a function to print content vs returning the content as a variable and then printing that instead

I have some classes to do things for a website like get news, create a discography of recordings, gig listings etc. There are functions for listGigs(), listHeadlines() etc and these print out the relevant info to the screen.
Is there a drawback to having a function return all the html as a variable and then printing this variable later instead of printing it out directly through a function call?
If I can set up all the content for each page in generic variables e.g. $maincontent then I can call these in a html template. It seems straight forward enough, I'm just wondering if this is good practice or not. Here is the general plan of what I am talking about anyway:
in the php file
$maincontent = $news->getHeadlines;
include_once 'template.php';
in the template file
<body>
<div>Some stuff</div>
<div clas="main"><?php echo $maincontent; ?></div>
</body>
I don't see any issue with creating direct to output widgets. If you wanted to be afforded a little more flexibility though you could implement something like this
function displayTemplate($template, $data, $__captureOutput = false){
if ($__captureOutput) ob_start();
extract ($data);
include($template);
if ($__captureOutput) return ob_get_clean();
}
and for your above use case you would just do either
$maincontent = $news->getHeadlines;
displayTemplate('template.php',array("maincontent"=>$maincontent));
or
$maincontent = $news->getHeadlines;
$data = displayTemplate('template.php',array("maincontent"=>$maincontent), true);
I'd question whether even returning HTML from the function would be wise.
The drawback of having the function output HTML is you've now coupled application (domain) logic with presentation logic. Suppose you want to present the same data in a different way, such as a JSON object or raw data to write to a file. You'd either have to write additional functions for each case or write a function that will parse the HTML, extract the data from it and convert it to the format you want.
If the function does the work but only returns a PHP data structure, then you can use that output as the input to another function that implements the presentation logic.
Printing HTML directly from the function is really inflexible, and you won't even have the option to reparse it into another format.
Good software is, as a rule, loosely coupled with the various concerns separated from each other. Computation of data and presentation of data are separate concerns.

Is it bad to use html inside a php class?

is there anything wrong with using html inside a class function? I call it in the DOM so I don't need a string returned.
public function the_contact_table(){
?>
<div>
some html here
</div>
<?php
}
Also when I do need the string I use this method? Is there a better way or is this relatively standard?
public function get_single(){
ob_start();?>
<div class='staff-member single'>
<div class='col left'>
<div class='thumbnail'>
thumbnail
</div>
<?php $this->the_contact_table(); ?>
</div>
<div class='col right'>
</div>
</div>
<?php
$content = ob_get_contents();
ob_end_clean();
return $content;
}
UPDATE
I should have explained why i am doing this. I'm making a Wordpress plugin and want to control a post types output. So I am using a filter like below
public function filter_single($content){
global $post;
if ($post->post_type == 'staff-member') {
$sm = new JM_Staff_Member($post);
$content = $sm->get_single();
}
return $content;
}
So as you can see, I must return a string to the wordpress core
You should be using HEREDOC instead of output buffering if you want to store a long string into a variable. It looks like this:
$content = <<<EOD
content here
EOD;
EOD can be anything, but note two important things:
It can't have any whitespace in front of it and it must be on it's own line
It shouldn't be a string that could be found within your content
If you are using PHP >= 5.3, then you should use NOWDOC, which does not parse for variable inside the doc (unless you need this). The only different with the syntax of NOWDOC is that the sentinel is enclosed in quotes:
$content = <<<'EOD'
content here
EOD;
The reason why I'd stray away from output buffering is that it prevents the server from chunking the data sent to the client. This means that requests will seem slower because instead of the content being progressively sent to the client and displayed, it is forced to be sent all at once. Output buffering is a hack for situations when functions carelessly echo data instead of returning it or a tool for certain applications with the specific need for it. I'd also imagine that you'd take a hit on execution time if you used output buffering (because it involves function calls) versus HEREDOCing the string into a variable or including a view.
Now to answer the question about whether it is appropriate, I would say that in an MVC application all HTML and other content should be contained within its own view. Then a controller can call a view to display itself and doesn't have to worry about knowing the code involved in displaying the view. You can still pass information (like titles, authors, arrays of tags, etc.) to views, but the goal here is separating the content from the logic.
That said, Wordpress templates and code looks pretty sloppy to begin with and loosely if not at all implements MVC so if it's too much work to create a view for this, I'd say the sloppiness would fit in with WP's style.
It's not a good practice in regard to the fact that you alienate front-end developers by placing what are actually "Views" inside of PHP class files. This was one of my biggest issues when I first started using PHP in general, is that I wanted to dynamically create content within classes. It's a great idea, but you want to do it in a way that allows many members of your team to work together as smoothly as possible ;].
You should probably have the content inside of a separate file called "staff-member-single.php", which you then call in your function
public function get_single(){
ob_start();
require_once('views/staff-member-single.php');
$content = ob_get_contents();
ob_end_clean();
return $content;
}
You'd refactor that into a reusable method typically though, so it'd look a little bit like..
public function get_single()
{
$string = $this->render_view_as_string('satff-member-single');
return $string;
}
public function render_view($view)
{
require('views/'.$view.'.php');
}
public function render_view_as_string($view)
{
ob_start();
$this->render_view($view);
$content = ob_get_contents();
ob_end_clean();
return $content;
}
I think it is good practice to use PHP only for logic of application and transmission some data to view layer (template engine). In accordance with this there are some patterns like MVC.

How to setup site-wide variables in php?

I want to define something like this in php:
$EL = "\n<br />\n";
and then use that variable as an "endline" marker all over my site, like this:
echo "Blah blah blah{$EL}";
How do I define $EL once (in only 1 file), include it on every page on my site, and not have to reference it using the (strangely backwards) global $EL; statement in every page function?
Most PHP sites should have a file (I call it a header) that you include on every single page of the site. If you put that first line of code in the header file, then include it like this on every page:
include 'header.php';
you won't have to use the global keyword or anything, the second line of code you wrote should work.
Edit: Oh sorry, that won't work inside functions... now I see your problem.
Edit #2: Ok, take my original advice with the header, but use a define() rather than a variable. Those work inside functions after being included.
Sounds like the job of a constant. See the function define().
Do this
define ('el','\n\<\br/>\n');
save it as el.php
then you can include any files you want to use, i.e
echo 'something'.el; // note I just add el at end of line or in front
Hope this help
NOTE please remove the '\' after < br since I had to put it in or it wont show br tag on the answer...
Are you using PHP5? If you define the __autoload() function and use a class with some constants, you can call them where you need them. The only aggravating thing about this is that you have to type something a little longer, like
MyClass::MY_CONST
The benefit is that if you ever decide to change the way that you handle new lines, you only have to change it in one place.
Of course, a possible negative is that you're calling including an extra function (__autoload()), running that function (when you reference the class), which then loads another file (your class file). That might be more overhead than it's worth.
If I may offer a suggestion, it would be avoiding this sort of echoing that requires echoing tags (like <br />). If you could set up something a little more template-esque, you could handle the nl's without having to explicitly type them. So instead of
echo "Blah Blah Blah\n<br />\n";
try:
<?php
if($condition) {
?>
<p>Blah blah blah
<br />
</p>
<?php
}
?>
It just seems to me like calling up classes or including variables within functions as well as out is a lot of work that doesn't need to be done, and, if at all possible, those sorts of situations are best avoided.
#svec yes this will, you just have to include the file inside the function also. This is how most of my software works.
function myFunc()
{
require 'config.php';
//Variables from config are available now.
}
Another option is to use an object with public static properties. I used to use $GLOBALS but most editors don't auto complete $GLOBALS. Also, un-instantiated classes are available everywhere (because you can instatiate everywhere without telling PHP you are going to use the class). Example:
<?php
class SITE {
public static $el;
}
SITE::$el = "\n<br />\n";
function Test() {
echo SITE::$el;
}
Test();
?>
This will output <br />
This is also easier to deal with than costants as you can put any type of value within the property (array, string, int, etc) whereas constants cannot contain arrays.
This was suggested to my by a user on the PhpEd forums.
svec, use a PHP framework. Just any - there's plenty of them out there.
This is the right way to do it. With framework you have single entry
point for your application, so defining site-wide variables is easy and
natural. Also you don't need to care about including header files nor
checking if user is logged in on every page - decent framework will do
it for you.
See:
Zend framework
CakePHP
Symfony
Kohana
Invest some time in learning one of them and it will pay back very soon.
You can use the auto_prepend_file directive to pre parse a file. Add the directive to your configuration, and point it to a file in your include path. In that file add your constants, global variables, functions or whatever you like.
So if your prepend file contains:
<?php
define('FOO', 'badger');
In another Php file you could access the constant:
echo 'this is my '. FOO;
You might consider using a framework to achieve this. Better still you can use
Include 'functions.php';
require('functions');
Doing OOP is another alternative
IIRC a common solution is a plain file that contains your declarations, that you include in every source file, something like 'constants.inc.php'. There you can define a bunch of application-wide variables that are then imported in every file.
Still, you have to provide the include directive in every single source file you use. I even saw some projects using this technique to provide localizations for several languages. I'd prefer the gettext way, but maybe this variant is easier to work with for the average user.
edit For your problem I recomment the use of $GLOBALS[], see Example #2 for details.
If that's still not applicable, I'd try to digg down PHP5 objects and create a static Singleton that provides needed static constants (http://www.developer.com/lang/php/article.php/3345121)
Sessions are going to be your best bet, if the data is user specific, else just use a conifg file.
config.php:
<?php
$EL = "\n<br />\n";
?>
Then on each page add
require 'config.php'
the you will be able to access $EL on that page.

Categories