Where should HTML be rendered in Object-Oriented PHP design? - php

Using Object-Oriented PHP, where should HTML be rendered?
The business processes include several actions to maintain customer records.
Should the rendering of each business process get a separate PHP file? ie. viewCustomerTransactions.php?
Where should code like this reside?
$custTrans = Customer.getTransactions();
foreach ($custTrans as $ct){
$amount = $ct[0];
$date = $ct[1];
$product = $ct[2];
echo '<div class="custTrans">';
echo '<span class="custTransAmount">'.$amount.'</span>';
echo '<span class="custTransDate">'.$date.'</span>';
echo '<span class="custTransproduct">'.$product.'</span>';
echo '</div>';
}
Perhaps an MVC framework like codeigniter would be better?

I'm still figuring out what's the best way to keep php and layout seperate without too much fuzz. For the moment I really like the include-templating approach, beacause it's so simple and has no restrictions.
So, for your example, you would have a php file (example.php) that looks like this:
<?php
$custTrans = Customer.getTransactions();
$displ_transactions = array();
foreach ($custTrans as $ct){
$transaction = array(
'amount' => $ct[0],
'date' => $ct[1];
'product' => $ct[2];
);
$displ_transactions[] = $transaction; // this will push the transacion into the array
}
include 'example.tpl.php'
?>
And then you need a second file (example.tpl.php):
<?php foreach ($displ_transactions as $transaction) { ?>
<div class="custTrans">
<span class='custTransAmount'><?php echo $transaction['amount'] ?></span>;
<span class='custTransDate'><?php echo $transaction['date'] ?></span>;
<span class='custTransproduct'><?php echo $transaction['product'] ?></span>;
</div>
<?php } ?>
Just call example.php in your browser and you will see the same result as you had before.
This is all good and well for small websites, because this method causes some overhead. If you are serious about templating, use smarty. it's easy to learn, and it has automatic caching, so it's super fast.
I just realize you can also do it this way:
example.php:
<?php
$custTrans = Customer.getTransactions();
foreach ($custTrans as $ct){
$amount = $ct[0];
$date = $ct[1];
$product = $ct[2];
include 'example.tpl.php';
}
?>
example.tpl.php:
<div class="custTrans">
<span class='custTransAmount'><?php echo $amount ?></span>;
<span class='custTransDate'><?php echo $date ?></span>;
<span class='custTransproduct'><?php echo $product ?></span>;
</div>
Use whatever suits you best :)

If I were you I would store the html in a variable instead of echoing it out like so:
$custTrans = Customer.getTransactions();
$html = "";
foreach ($custTrans as $ct){
$amount = $ct[0];
$date = $ct[1];
$product = $ct[2];
$html .= "<div class="custTrans">";
$html .= "<span class='custTransAmount'>".$amount."</span>";
$html .= "<span class='custTransDate'>".$date."</span>";
$html .= "<span class='custTransproduct'>".$product."</span>";
$html .= "</div>";
}
You then have this html data stored in the variable $html and you can echo it out where ever you like.
echo $html;
Does that solve you problem mate?
W.

I would have to confirm that the include-templating (mentioned by Jules Colle) is one of the answers, nevertheless, it might get messy to maintain when the project is too large, so keep in mind to document what file is included by what file, since there is (currently) no (free) IDE solution to this type of chaining... a solution that would easily bring you from one file to another or simply lay-out everything into a procedural-like code.
Edit:
do not forget the magic constants:
http://www.php.net/manual/en/language.constants.predefined.php
and this:
$_SERVER['DOCUMENT_ROOT']

Related

PHP: Which is more efficient: a concatonated return variable, or returning each line individually?

I have a sytem where I want to build an HTML table in PHP from data retrieved from a databse.
I've previously used two different methods for creating the HTML and echoing it.
Building a return variable, and echoing at the end of the PHP script:
<?php
$data['category']['parts']; // format of the data
$retval = '<table>';
foreach($data as $category) {
$retval .= '<tr>';
foreach($category as $data) {
$retval .= '<td>'.$data.'</td>'
}
$retval .= '</tr>';
}
$retval .= '</table>';
echo $retval;
The other method is to echo each line as the code comes to it:
<?php
$data['category']['parts']; // format of the data
echo '<table>';
foreach($data as $category) {
echo '<tr>';
foreach($category as $data) {
echo '<td>'.$data.'</td>'
}
echo '</tr>';
}
echo '</table>';
Which of the two methods is more efficient, in terms of processor/memory usage, and also for processing speed?
Is there actually a real difference, rather than just a question of style?
My shot is: whatever you find more readable. Impact on performance is so small that probably you won't see any difference.
However, if you really care, echo should be faster (nothing better than a performance test on your specific scenario) because string concatenation will resize retval multiple times (and this will impact performance).
Even better you should avoid concatenation also in your echo:
<?php
$data['category']['parts']; // format of the data
echo '<table>';
foreach($data as $category) {
echo '<tr>';
foreach($category as $data) {
echo '<td>', $data, '</td>';
}
echo '</tr>';
}
echo '</table>';
Do you want to do better? Just construct your own string builder object (but, honestly, gain is so small that you should seriously consider if worth your effort).
If you want to use kind of a templating to generate your page, I would rewrite your code to something like this.
(this can be in a dedicated file, and just included to display output)
<?php
$data['category']['parts']; // format of the data
?>
include ('templates/theFileIWantToShow.php');
---- snip files here. Processing above, template bellow.
<table>
<?foreach($data as $category):?>
<tr>
<?foreach($category as $data):?>
<td><?=$data?></td>
<?endforeach;?>
</tr>
<?endforeach;?>
</table>
This would offer (imho) best readability when it comes down to large html pages with only a few wildcards.
Advantages:
You get clean html with only a few spots of php in between
You can easily replace the template files without touching the generating code
you can reuse templates. Providing direct output and/or building strings is a mess, when it comes down to reuse the same html-markup for a certain element over and over.
Note that this requires shorttags to be enabled in your php.ini for PHP < 5.4.0.

Creating a variable template to display a database content

I'm working on a database website currently and part of the project is to display the content of a database in a custom form using pixels to position the various fields.
I am however having trouble getting the code to work as the way I'm creating the form doesn't seem to work in a php tag, but It requires a WHILE loop in order to continue running until the database field is empty.
I'm only including the relevant code section so as to not clog up the post, all my coding is segmented so I can isolate bugs.
<?php
$usernameh = 20;
$units = "px";
for ($x=0; $x<=2; $x++) {
$pix=$value . $units;
<div style="position:absolute;left:10px;top:20px;width:100px;height:20px;z- index:5;text-align:left;">
<span style="color:#000000;font-family:Arial;font-size:15px;">Field Name:</span></div>
$value += 150;
}
?>
The idea is to substitute the 20px on the first line of the divcommand with $pix so that with each iteration the value increases by a set amount and separates out the entries.
I'm very new to php coding, as in only really started 2 weeks ago. I'm sure there is a simple solution to this but I'm not sure what question to ask Google to get the response I'm after.
I hope my problem makes sense. The database is in MySQL but all that is fine, its just the formatting I'm struggling with. Even without using a variable in the formatting code the script crashes while the php tag is in effect.
Can anyone offer any advice on where my problem is or suggest another alternative to this.
Thanks!
You need to break out of PHP ?> before HTML and then switch back to PHP <?php before more PHP code
$value = 20;
$units = "px";
for ($x=0; $x<=2; $x++) {
$pix = $value . $units;
?>
<div style="position:absolute;left:10px;top:<?php echo $pix ?>;width:100px;height:<?php echo $pix ?>;z- index:5;text-align:left;">
<span style="color:#000000;font-family:Arial;font-size:15px;">Field Name:</span></div>
<?php
$value += 150;
}
Or for the HTML you can echo it from PHP:
echo '<div style="position:absolute;left:10px;top:' . $pix . ';width:100px;height:' . $pix . ';z- index:5;text-align:left;">
<span style="color:#000000;font-family:Arial;font-size:15px;">Field Name:</span></div>';

Create a search box that search between id of divs

Well I’m kind of new in this with web programing and I’m sure I’m breaking some rules but I really need a hand here. Well the idea it’s that I have created a slider with the information that I bring from the data base, so I’m working with php and I’m making that a piece of code in php fills all the li and divs for the slider, and I’m giving the id to the div that contains all the details the name of the user of the data base, so the deal it’s that I have to have a search field that looks through all the divs I have, and after the search it only display the name of the user you are looking in the search field.
So this is the code I have of php that’s in the page, well I try to use an ajax but when the information comes from the php file it doesn’t respect the size of the div and prints all the information and I don’t get the slider.
<div class="slider" id="slider">
<?php
$cont = 0;
$bandera=0;
$tamano = 0;
$nombreUsuario = "";
$arrayIDs = array();
$i = 0;
$query_Total = "SELECT u.FOTO_HIJO_USUARIOS, u.ID_USUARIOS, u.NOMBRE_USUARIOS, u.NOMBRE_HIJO_USUARIOS, u.FB_ID_USUARIOS, m.ID_MOMENTOS_MAGICOS, m.TEXTO_MOMENTOS_MAGICOS FROM MOMENTOS_MAGICOS AS m, USUARIOS AS u WHERE u.ID_USUARIOS = m.ID_USUARIOS AND u.ESTADO_USUARIOS = '1'";
$todas_Total = mysql_query($query_Total, $MM_db) or die(mysql_error());
echo "<ul>";
while(($row = mysql_fetch_array($todas_Total, MYSQL_ASSOC))){
$nombreUsuario = $row['NOMBRE_USUARIOS'];
$arrayIDs[$i] = $nombreUsuario;
$i++;
$bandera++;
if($cont++%3==0){
echo '<li>';
}
echo '<div class="participantes" id="'.$nombreUsuario.'" style="float:left; padding-left:10px;width:145px;margin-right:25px;margin-left:15px; margin-top:15px">';
echo '<div class="face_foto"><img src="https://graph.facebook.com/'.$row['FB_ID_USUARIOS'].'/picture" width="52" height="52" /></div>';
echo '<h1 align="right">'.$nombreUsuario.'</h1>';
echo '<img class="bebe_participante" src="uploads/'.$row['FOTO_HIJO_USUARIOS'].'" width="153" height="89" />';
echo '<h2 align="center">'.$row['NOMBRE_HIJO_USUARIOS'].'</h2>';
echo '<div id="botMas"> <img class="img_votos" src="images/bt_ver_mas.png" width="89" height="35"/> </div>';
$query_Votos = "SELECT COUNT( * ) AS VOTOS FROM VOTOS WHERE ID_MOMENTOS_MAGICOS = '".$row['ID_MOMENTOS_MAGICOS']."'";
$todos_Votos = mysql_query($query_Votos, $MM_db) or die(mysql_error());
while(($row = mysql_fetch_array($todos_Votos, MYSQL_ASSOC))){
echo '<div class="votos">'.$row['VOTOS'].' VOTOS </div>';
}
echo '</div>';
$tamano++;
}
if($cont%3==0 || $cont==$bandera ){
echo '</li>';
}
echo "</ul>";
?>
</div>
So I was thinking of making the search with javascript or jquery, but after some tries I haven’t been able to make it.
So I really hope you guys can help me.
Thank you for your time :)
Use http://ivaynberg.github.com/select2/ for this.
See: Many-to-Many Ajax Forms (Symfony2 Forms) for an implementation (ignore the fact that this is tagged symfony2, it is relevant to php as well)

Better way to create html code from php variables?

My website consists of many products that are each contained in a div with the id content block. The link, image, background, description and price are all loaded from a mySQL table. My original plan was to save the below html code as a string and loop over the rows in the mySQL table filling the string I created with php/mySQL values.
I was wondering if I am going about this the right way, or is there a better way to create html code from php variables?
<div id="contentblock" style="background-image:url(images/$BACKGROUND.png);">
<div id="picture"><img src="$IMAGELINK"/></div>
<div id="description"><p>$DESCRIPTION</p></div>
<div id="price"><p class=price>$PRICE</p></div>
</div>
Firstly PHP is a template engine - in my experience template engines that layer ontop of PHP are only good for the simplest of cases and are easily outgrown.
Secondly the original code is as good as any method. At risk of stating the obvious to make it better abstract it into a function;
function output_block($BACKGROUND, $LINK, $IMAGELINK, $DESCRIPTION, $PRICE)
{
echo "<div id='contentblock' style='background-image:url(images/$BACKGROUND.png);'>
<div id='picture'><a href='$LINK'><img src='$IMAGELINK'/></a></div>
<div id='description'><p>$DESCRIPTION</p></div>
<div id='price'><p class=price>$PRICE</p></div>
</div>";
}
If you want to make it much better then adopt a framework, an entire admin config page is show below. All of the HTML glue is provided by the framework - the following code is real, but really to illustrate how a framework can provide a lot of the grunge work for you.
In the example below if I want to edit a single entity I'd change the TableViewEdit into a FormView and provide an instance of an entity rather than an iterable list.
$entity = new CbfConfig(); // Database entity
$page = new AdminWebPage("Site Configuration"); // Page for output
/*
* build the view
*/
$vil = new ViewItemList();
$col = &$vil->add(new ViewItem("description","Description"));
$col->get_output_transform()->allow_edit(false); // this field cannot be editted
$col = &$vil->add(new ViewItem("value","Value"));
$v1 = new TableViewEdit($entity, $vil,"admin_values"); // present as standard editable table
/*
* output the page
*/
$page->begin();
$iterable_list = CbfConfig::site_begin();
$page->add_body($v1->get_output($iterable_list,'admin_config'));
$page->end();
Id just have all my html code outside of php tags, then whereever I need a variable from php do as follows
<div id="description"><p><?php echo $DESCRIPTION; ?></p></div>
You can loop around non php code too. For example
<?php
for($i = 0; $i < 10; $i++) {
?>
<div id="description"><p><?php echo $i; ?></p></div>
<?php
} //end for loop
?>
Obviously this is just an example.
well if im without a template engine for somereason i usually do something like:
function partial($file, $args = array()) {
extract($args);
ob_start();
include($file);
return ob_get_clean();
}
Really, there are 3 ways of doing this. Use whichever is easiest for you in the context that you are using it in.
<?php
while(($row=mysql_fetch_assoc($result))!==false)
{
echo "<div>{$row['fieldName']}</div>";
}
?>
<?php
while(($row=mysql_fetch_assoc($result))!==false)
{
echo '<div>'.$row['fieldName'].'</div>';
}
?>
<?php
while(($row=mysql_fetch_assoc($result))!==false)
{
?>
<div><?= $row['fieldName']; ?></div>
<?php
}
?>

Stripping Specific HTML & Content from a page with PHP for RSS

I am building a mobile version of my company website, and one thing we are in need of is an RSS feed.
I have the RSS pulling in fine with this code:
<?php
$url = 'http://www.someurl.com/rss/articles';
$feed = simplexml_load_file($url, 'SimpleXMLIterator');
$filtered = new LimitIterator($feed->channel->item, 0, 15);
foreach ($filtered as $item) { ?>
<li data-icon="false">
<h2><?php echo $item->title; ?></h2>
<p class="desc"><?php echo $item->description; ?></p>
<br />
<p class="category"><b><?php echo $item->category; ?></b></p>
<a class="link" href="<?php echo $item->link; ?>">Read More</a>
<br />
<p class="pubDate"><?php echo $item->pubDate; ?></p>
<br />
</li>
<?php } ?>
What I would like to do is utilize either the fopen() or file_get_contents() to handle the clicking of the 'Read More' link and strip all of the contents of the incoming page except for the <article> tag.
I have searched Google the past day, and have not been successful in finding any tutorials on this subject.
EDIT:
I would like to load the stripped HTML contents into their own view within my framework.
SECOND EDIT:
I would just like to share how I solved this problem.
I modified my $item->link; to be passed through the URL as a variable:
Read More
On the article.php page, I collect the variable with a if() statement:
if (isset($_GET['rss_url']) && is_string($_GET['rss_url'])) {
$url = $_GET['rss_url'];
}
Then building on the suggestions of the comments below, I built a way to then collect the incoming URL and strip the necessary tags to then format for my mobile view:
<div id="article">
<?php
$link = file_get_contents($url);
$article = strip_tags($link, '<title><div><article><aside><footer><ul><li><img><h1><h2><span><p><a><blockquote><script>');
echo $article;
?>
</div>
Hopefully this helps anyone else who may encounter this problem :)
I'm not sure if I understand it correctly but are you trying to output the contents on the current page whenever someone clicks the more link?
I would probably use Javascipt to do that, maybe jQuery's .load() function which loads html from another page and allows you to load only specific fragments of a page.. but if you need to use php I would look into Simple HTML DOM Parser
$html = file_get_html($yourUrl);
$article = $html->find('article', 0); // Assuming you only have 1 article/page
echo $article;
The only way I can see is to set up your own separate script to route the links through.
So, instead of echo $item->link use
echo 'LinkProcessor.php?link='.$item->link
Then, setup a script called LinkProcessor.php and use file_get_contents on that page. You can then process the XML to only show the article tag and echo the results:
$article = file_get_contents($_GET['link']);
$xml = new SimpleXMLElement($article);
$articleXml = $xml->xpath('//article');
echo articleXml[0];
Note that the code is untested, but it should be OK.

Categories