...

View Full Version : Separating PHP and HTML



WingTsun
01-11-2012, 12:15 PM
Hello to everyone!

I have working as a web-site developer for a while now. I have been mixing HTML, PHP, JS, and more .. all together. One by one, project by project I have started to make them more and more separate. Now its time to separate them completely.

And here is the problem, I can not find the best way to to that. I do not want to use any of the Frameworks. I want to make a clean code.

Here is a smell of my last structure :

core.php




// All kind of Main Functions

function page() {
return substr($_SERVER["SCRIPT_NAME"],strrpos($_SERVER["SCRIPT_NAME"],"/")+1); }

function getExtension($str) {

$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}


classes/exchange.php



class exchange {

public $method;

function rewrite_mehod_name_full() {

global $global;

$method = $this -> method;
$method = $global['global']['payMethod_full'][$method];
return $method;
}

function rewrite_mehod_name_short() {

global $global;

$method = $this -> method;
$method = $global['global']['payMethod_short'][$method];
return $method;
}

function rewrite_mehod_currency() {

global $global;

$method = $this -> method;
$currency = $global['global']['payMethod_currency'][$method];
return $currency;
}
}

$objekts = new exchange;


regular_page.php




include('../includes/core.php');
include("../class/exchange.php");
include("../header.php");

<table border="0" cellspacing="0" cellpadding="0" class="history">

<tr class="head">

<!-- <td> <? echo $global['history']['table']['title']['nr']; ?> </td> -->
<td> <? echo $global['history']['table']['title']['date']; ?> </td>
<td> <? echo $global['history']['table']['title']['from_method']; ?> </td>
<td> <? echo $global['history']['table']['title']['from_amount']; ?> </td>
<td> <? echo $global['history']['table']['title']['to_method']; ?> </td>
<td> <? echo $global['history']['table']['title']['to_amount']; ?> </td>
<td> <? echo $global['history']['table']['title']['state']; ?> </td>
<td> </td>

</td>

<?
if($_bills) {

while($bill = mysql_fetch_array($bills)){

$objekts -> method = $bill['from_method'];
$objekts2 -> method = $bill['to_method'];

$height = '580';
$width = '650';

echo "<tr class='bill'>";
//echo "<td onClick=window.open('history_view.php?id=".$bill['id']."','villexchange','width=450,height=500')>".$bill['nr']."</td>";
echo "<td onClick=window.open('history_view.php?id=".$bill['id']."','villexchange','width=".$width.",height=".$height."')>".date("j.n.Y", $bill['date'])."</td>";
echo "<td onClick=window.open('history_view.php?id=".$bill['id']."','villexchange','width=".$width.",height=".$height."')>".$objekts -> rewrite_mehod_name_short()."</td>";
echo "<td onClick=window.open('history_view.php?id=".$bill['id']."','villexchange','width=".$width.",height=".$height."')>".format_2($bill['from_amount'])." ".$objekts -> rewrite_mehod_currency()."</td>";
echo "<td onClick=window.open('history_view.php?id=".$bill['id']."','villexchange','width=".$width.",height=".$height."')>".history_rewrite_method($bill['to_method'])."</td>";
echo "<td onClick=window.open('history_view.php?id=".$bill['id']."','villexchange','width=".$width.",height=".$height."')>".format_2($bill['to_amount'])." ".$objekts2 -> rewrite_mehod_currency()."</td>";
echo "<td onClick=window.open('history_view.php?id=".$bill['id']."','villexchange','width=".$width.",height=".$height."')>".history_rewrite_state($bill['state'])."</td>";
echo "<td> <a href='history_view.php 'onClick='window.print(); return false;'> <img src='images/print_a.png' width='16' height='16' /> </a> </td>";
echo "</tr>";

}
}

else {

echo "<tr><td colspan='8' align='center'> ".$global['history']['table']['data']['empty'].". </td></tr>";
}

?>

</table>


So please help my to find the best way to structurize my web-sites. Thank you!

XmisterIS
01-11-2012, 12:32 PM
DOM is your friend. It takes a bit of figgledy-piggledy but it does the job!

WingTsun
01-11-2012, 12:47 PM
DOM is your friend. It takes a bit of figgledy-piggledy but it does the job!


Thank you for the reply! But I do not this this what I was searching for, as far as I understand. Maybe you could give me a simple example of DOM usage here ? :)

Dormilich
01-12-2012, 06:54 AM
I'm not sure what the best way is, but depending on the situation I use the following.
- global HTML template: make a HTML file with placeholders (I go along with {{<token>}}) and do a str_replace() on the tokens
- JavaScript: gets its own files. today there is no need to use inline JS.
- database data: some of PHP's database functions allow you to populate a class with fetched data (PDO, probably MySQLi as well)
- nested HTML elements: using DOMDocument. pretty much the same as if I would create the structures in JS.
- repeated HTML structures (list items, table rows) can be predefined and then populated with data via sprintf()

and some general points:
- globals do not go well with OOP. that's bad practice (violating the data encapsulation and integrity principle)
- mysql_* functions are outdated, use PDO or MySQLi instead
- $globals is an array with 4 nested levels, there's certainly room to improve your data model

fatecaresx13
01-12-2012, 07:36 AM
If you're good with regular expressions you could honestly write your own templating system. I like Smarty a lot however, I know you mentioned no templates. :P

It is nice to basically code out your page


<html>
<title>{TITLE}</title>
</html>

and use output buffering to replace as necessary.

:)

WingTsun
01-12-2012, 08:19 AM
Thank you for the answers! Yes, I would not want to use a Frameworks like "Smarty", since there will be so much code I will not ever use, but I could create a simple template for myself. Maybe anyone could share a simple example of that ? By writing it from 0, I am sure I will miss something important, since I have never done that..

WingTsun
01-12-2012, 08:00 PM
Sorry for repeating, but I could not don't do that :P

So, any other tips from anyone ? :)

Dormilich
01-12-2012, 08:13 PM
I use this class to process my templates:

<?php
/*
* TemplateRitter.php
*
* Copyright 2009 - 2011 Bertold von Dormilich <Dormilich at netscape dot net>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/

namespace Dormilich\System\HTML;
use Dormilich\Interfaces as IFC;

class TemplateRitter implements IFC\iRender, IFC\iParameter
{
/**
* @var (string) $html HTML source code
* @var (string) $tag_open left-side placeholder delimiter
* @var (string) $tag_close right-side placeholder delimiter
* @var (Array) $placeholders full placeholder (key) and
* replacement value
* @var (Array) $preg_delims possible internal PCRE delimiters
*/
private
$html
, $tag_open = '{{'
, $tag_close = '}}'
, $placeholders = array()
, $preg_delims = array('/', '#', '|', '@')
;
/**
* @const (int) TAG_OPEN option key for ->tag_open
* @const (int) TAG_CLOSE option key for ->tag_close
*/
const # use primes > 1024 !
TAG_OPEN = 1031
, TAG_CLOSE = 1033
;

/**
* Sets the HTML source code and options (placeholder delimiters).
* Parses the placeholders from the HTML.
*
* @param (string) $tpl HTML source code with placeholders
* @param (Array) $options options (placeholder opening/closing
* delimiters)
*/
public function __construct(
$tpl
, Array $options = array()
)
{
if (is_readable($tpl))
{
$tpl = file_get_contents($tpl);
}
$this->html = (string) $tpl;
$this->setOptions($options);
$this->parseTemplate();
}

/**
* Allows to get the placeholder values via pseudo-property.
*
* @param (string) $key placeholder name
* @return (string) placeholder value
*/
public function __get($key)
{
return $this->getParameterValue($key);
}

/**
* Allows to set the placeholder values via pseudo-property.
*
* @param (string) $key placeholder name
* @param (string) $value placeholder replacement text
* @return (void)
*/
public function __set($key, $value)
{
$this->setParameterValue($key, $value);
}

/**
* Sets the options (placeholder delimiters).
*
* @param (Array) $options options (placeholder opening/closing
* delimiters)
* @return (void)
*/
private function setOptions(
Array $options
)
{
if (isset($options[TemplateRitter::TAG_OPEN]))
{
$this->tag_open = (string) $options[TemplateRitter::TAG_OPEN];
}
if (isset($options[TemplateRitter::TAG_CLOSE]))
{
$this->tag_close = (string) $options[TemplateRitter::TAG_CLOSE];
}
}

/**
* Parses the placeholders from the HTML code.
*
* @return (void)
* @throws (OutOfBoundsException) all internal PCRE delimiters contained
* in the placeholder delimiters
*/
private function parseTemplate()
{
// determine PCRE delimiters
$preg_delim_invalid = $this->tag_open . $this->tag_close;
$preg_delim = false;
foreach ($this->preg_delims as $delimiter)
{
if (false === strpos($preg_delim_invalid, $delimiter))
{
$preg_delim = $delimiter;
break;
}
}
if (false === $preg_delim)
{
throw new \OutOfBoundsException("Placeholder delimiters interfer with the internal PCRE delimiters.");
}
// parse HTML code
$pattern = sprintf('%1$s(%2$s\w+%3$s)%1$s', $preg_delim, $this->tag_open, $this->tag_close);
preg_match_all($pattern, $this->html, $keys, \PREG_PATTERN_ORDER);

// create placeholder array with empty default values
$this->placeholders = array_combine($keys[1], array_fill(0, count($keys[1]), ''));
}

/**
* Gets the text value for a placeholder.
*
* @param (string) $name placeholder name w/o delimiters
* @return (string) placeholder name exists in the template
*/
public function getParameterValue(
$name
)
{
$key = $this->tag_open . $name . $this->tag_close;
if (isset($this->placeholders[$key]))
{
return $this->placeholders[$key];
}
return NULL;
}

/**
* Sets the text value for a placeholder.
*
* @param (string) $name placeholder name w/o delimiters
* @param (string) $value placeholder value
* @return (bool) placeholder name exists in the template
*/
public function setParameterValue(
$name
, $value
)
{
$key = $this->tag_open . $name . $this->tag_close;
if (isset($this->placeholders[$key]))
{
$this->placeholders[$key] = (string) $value;
return true;
}
return false;
}

/**
* Sets multiple placeholder values in one go. Non-existent placeholders
* are silently ignored.
*
* @param (Array) $params array of placeholder name-value pairs
* @return (int) number of set placeholders
*/
public function setParameterArray(
Array $params
)
{
$count = 0;
foreach ($params as $name => $value)
{
$count += (int) $this->setParameterValue($name, $value);
}
return $count;
}

/**
* Replace the placeholders in the HTML source code with the passed
* values.
*
* @return (string) final HTML source code
*/
public function render()
{
$placeholders = array_keys($this->placeholders);
$replacements = array_values($this->placeholders);
return str_replace($placeholders, $replacements, $this->html);
}
}

<?php
namespace Dormilich\Interfaces;

interface iRender
{
public function render();
}

<?php
namespace Dormilich\Interfaces;

interface iParameter
{
public function setParameterValue($name, $value);
public function setParameterArray(Array $values);
}

WingTsun
01-12-2012, 11:30 PM
Thank you Dormilich! I will test this out right in my next Project! I added a "Thank you" for your post.

I think my question is answered, and it could be set to "RESOLVED". But still, I will wait for maybe any other Alternative method, by someone else, who's so kind.. :)

Thank you!



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum