Templates o.o

Templates without frameworks...

Page 1 of 1

14 Replies - 863 Views - Last Post: 10 June 2009 - 08:53 AM Rate Topic: -----

#1 ShaneK  Icon User is offline

  • require_once("brain.php"); //Fatal error :/
  • member icon

Reputation: 239
  • View blog
  • Posts: 1,224
  • Joined: 10-May 09

Templates o.o

Posted 09 June 2009 - 01:55 PM

Greetings

Anyone know the best way to create a template that I can easily change without using a framework? I expect to start working on a project soon and I'll really need something like this...I used to use Dreamweaver for this sole purpose, actually, but recently I had to reinstall Vista and now I CBA....

So...any ideas? I don't really wanna take the time to learn an entire framework right now, if it's avoidable...

Any help on this subject would be appreciated :)

Yours,
Shane~

Is This A Good Question/Topic? 0
  • +

Replies To: Templates o.o

#2 CTphpnwb  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 2834
  • View blog
  • Posts: 9,737
  • Joined: 08-August 08

Re: Templates o.o

Posted 09 June 2009 - 02:07 PM

What are you looking for in a template?

I start all my php code with the assumption that I'll have a class definition followed by session_start, some code to determine if an objects been created and stored in a session variable, create it if necessary, then controlling code, and finally store the session variable(s). I have some small example files that I sometimes edit to speed things up, but other than that, the major part of writing the code is creating the methods.
Was This Post Helpful? 0
  • +
  • -

#3 ShaneK  Icon User is offline

  • require_once("brain.php"); //Fatal error :/
  • member icon

Reputation: 239
  • View blog
  • Posts: 1,224
  • Joined: 10-May 09

Re: Templates o.o

Posted 09 June 2009 - 02:14 PM

I'm actually talking about the ability to massively edit the looks and layout of a site without a framework XD

Yours,
Shane~
Was This Post Helpful? 0
  • +
  • -

#4 CTphpnwb  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 2834
  • View blog
  • Posts: 9,737
  • Joined: 08-August 08

Re: Templates o.o

Posted 09 June 2009 - 02:24 PM

Well, since you're asking in the php forum, you must not mean css. If you don't have a framework, then it's really up to how you write your code. I know there's a school of thought against this, but I like to put my html in my methods because that allows me to change things in multiple places simultaneously by changing a single method.
Was This Post Helpful? 0
  • +
  • -

#5 ShaneK  Icon User is offline

  • require_once("brain.php"); //Fatal error :/
  • member icon

Reputation: 239
  • View blog
  • Posts: 1,224
  • Joined: 10-May 09

Re: Templates o.o

Posted 09 June 2009 - 02:30 PM

I was considering an HTML class or something...do you think that would work?

Like...
<?php
class html {
	public function header(){
		   print "<html> (blah blah blah blah)";
	}

	public function footer(){
		  print "(blah blah blah) </html>";
	}
}


Then include the class and before and after my code I could call those functions to output my HTML data...and if I ever needed to change it I'd just change the class?

Think that'd be smart? lol

Yours,
Shane~
Was This Post Helpful? 0
  • +
  • -

#6 CTphpnwb  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 2834
  • View blog
  • Posts: 9,737
  • Joined: 08-August 08

Re: Templates o.o

Posted 09 June 2009 - 02:38 PM

You could do that, but I tend to look at php as a batch file. It gets run and it's done. Then it gets run again, and it's done. For this reason, I rarely (never?) see a need to have an extra class hanging around. I rarely extend one either. I'll just toss the needed methods into my class. I suppose that could be using extra memory, especially when I store an object in a session variable...
Was This Post Helpful? 0
  • +
  • -

#7 AdaHacker  Icon User is offline

  • Resident Curmudgeon

Reputation: 452
  • View blog
  • Posts: 811
  • Joined: 17-June 08

Re: Templates o.o

Posted 09 June 2009 - 02:42 PM

View PostShaneK, on 9 Jun, 2009 - 03:14 PM, said:

I'm actually talking about the ability to massively edit the looks and layout of a site without a framework XD

Well, that doesn't really narrow it down any. You're going to have to be a little less general.

There are plenty of ways to do templates in PHP. After all, PHP itself can be used as a template system. For example, this article describes how you can build a simple, light-weight template engine using regular PHP files as your templates. You can do the same thing in a slightly less organized way simply by include()ing template files in the appropriate places. The best approach depends on what you need and how your application is structured, but everything you need is built right into plain, vanilla PHP.
Was This Post Helpful? 0
  • +
  • -

#8 CTphpnwb  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 2834
  • View blog
  • Posts: 9,737
  • Joined: 08-August 08

Re: Templates o.o

Posted 09 June 2009 - 02:52 PM

View PostAdaHacker, on 9 Jun, 2009 - 05:42 PM, said:

For example, this article describes how you can build a simple, light-weight template engine using regular PHP files as your templates.

:pirate:

From that link, and this is the kind of thing I'll go miles out of my way to avoid:
<table>  
   <tr>  
	   <th>Id</th>  
	   <th>Name</th>  
	   <th>Email</th>  
	   <th>Banned</th>  
   </tr>  
<? foreach($user_list as $user): ?>  
   <tr>  
	   <td align="center"><?=$user['id'];?></td>  
	   <td><?=$user['name'];?></td>  
	   <td><a href="mailto:<?=$user['email'];?>"><?=$user['email'];?></a></td>  
	   <td align="center"><?=($user['banned'] ? 'X' : '&nbsp;');?></td>  
   </tr>  
<? endforeach; ?>  
</table>



The thought of searching through pages of that to alter something makes me shudder. I'd much rather go through well-written OOP.
Was This Post Helpful? 0
  • +
  • -

#9 RPGonzo  Icon User is offline

  • // Note to self: hmphh .... I forgot
  • member icon

Reputation: 151
  • View blog
  • Posts: 954
  • Joined: 16-March 09

Re: Templates o.o

Posted 09 June 2009 - 03:05 PM

The OOP method would be the cleanest... after that a dynamic CSS sheet would be in order to make the visible changes ... and a easy way of making a dynamic CSS sheet is actually laying it out like a PHP file

<?php
header("Content-type: text/css");
?>



that at the beginning of a PHP file will turn its contents into a CSS sheet from there you can either organize it in OOP or a simple switch...

Personally i cannot stand tables ... i absolutely DESPISE them ... and saying that DIVS are easier ( in my opinion ) to style anyways...

This may not even be what your looking for but i thought i would chime in .... :)
Was This Post Helpful? 0
  • +
  • -

#10 RudiVisser  Icon User is offline

  • .. does not guess solutions
  • member icon

Reputation: 1001
  • View blog
  • Posts: 3,555
  • Joined: 05-June 09

Re: Templates o.o

Posted 09 June 2009 - 03:31 PM

Here's the styling class from our BB/Forum system (not yet released...). It's fairly simple so can easily be adapted for very simple use, the only real function you'll need to call is parseTemplate.

It's fairly powerful in that it can read files, it will "compress" the data it outputs, perform simple conditional statements, output PHP Variables, contain and output blocks (repeated data defined in code as an array).

EDIT: Gonna post this as a snippet too actually :)

<?php
	/*#NOTICE:1#*/
	
	/**
	* Styles class.
	*
	* Produces templated versions of MageBB in a procedural style taken from the style.config file in the style directory.
	* Will fallback to style 'magebb' when there is no style set in the Administration Panel.
	*
	* Will automatically replace variables in the template files which are accessed by $magebb{varname}.
	*
	* Blocks are accessed via $openBlock{blockname} and from there on $blockItem{varname} for the variable values (Translates into a for loop).
	**/
	class Styles {
		
		/**
		* Stores the single replacement variables (named) -> $variables['varname'] = 'replacement';
		*
		* @var	array	Variables
		**/
		private $Variables;
		
		/**
		* Stores the blocks of data (named) -> $blocks['name'][0]['varname'] = 'replacement';
		*
		* @var	array	Blocks
		**/
		private $Blocks;
		
		/**
		* Style Data such as copyright, name, etc.
		*
		* @var	array	StyleData
		**/
		public $StyleData;
		
		/**
		* Template names -> $templates['header'] = 'header.inc';
		*
		* @var	array	Templates
		**/
		private $Templates;
		
		/**
		* Reference to the active MageBB object
		*
		* @var	object	MageBB
		**/
		private $MageBB;
		
		/**
		* Setup and parse the style from $MageBB->Settings
		*
		* @param	object	MageBB
		**/
		public function __construct(&$MageBB) {
			$this->MageBB = $MageBB;
			// Now all done from Session
			//$styleName = $this->MageBB->Settings->AllSettings['style_name'];
			$styleName = $this->MageBB->Sessions->CurrentData['style'];
			if(!file_exists(ROOT . "styles/" . $styleName . "/style.config")) $styleName = "magebb";
			if(!file_exists(ROOT . "styles/" . $styleName . "/style.config")) triggerCritical(CRIT_FILESTRUCTURE, "Style '" . $styleName . "'s style.config file does not exist.");
			$configContents = file_get_contents(ROOT . "styles/" . $styleName . "/style.config");
			$xml = new SimpleXMLElement($configContents);
			$this->StyleData = array();
			$this->StyleData['FolderName'] = $this->MageBB->Settings->AllSettings['style_name'];
			$this->StyleData['Name'] = (string)$xml->name;
			$this->StyleData['Copyright'] = (string)$xml->copyright;
			$this->StyleData['Site'] = (string)$xml->site;
			$this->StyleData['Version'] = (int)$xml->version;
			$this->StyleData['ForBuild'] = (int)$xml->magebbBuild;
			$this->StyleData['StyleSheet'] = (string)$xml->stylesheet;
			// Now parse templates
			$this->Templates = array();
			foreach($xml->templates->template As $template) {
				$this->Templates[(string)$template->name] = array('RealName' => (string)$template->realName, 'FileName' => (string)$template->fileName);
			}
			$this->initialiseParser();
		}
		
		/**
		* Setup replacement variable parser
		**/
		private function initialiseParser() {
			// From settings
			$this->Variables['boardtitle'] = $this->MageBB->Settings->AllSettings['board_name'];
			$this->Variables['pagetitle'] = $this->MageBB->Settings->AllSettings['board_name'];
			$this->Variables['date'] = date($this->MageBB->Settings->AllSettings['date_format']);
			$this->Variables['genseconds'] = 0;
			$this->Variables['querycount'] = &$this->MageBB->Database->queryCount;
			$this->Variables['stylesheet'] = "styles/".$this->StyleData['FolderName']."/".$this->StyleData['StyleSheet'];
			$this->Variables['imagedir'] = "styles/".$this->StyleData['FolderName']."/images/";
			$this->Variables['bbjs'] = "includes/js/javascriptinclude.php";
			// We might aswell generate the generic style variables here
			$this->Variables['copyrightnotice'] = "Powered by <a href=\"http://www.magebb.com/\">MageBB</a> Version ".$this->MageBB->Version.".<br />Copyright &copy; 2002-2008 <a href=\"http://www.mageuk.com/\">Mage UK Ltd</a>.";
			$avgs = $this->MageBB->Compat->LoadAverages();
			$this->Variables['loadavg'] = $avgs[0] . ", " . $avgs[1] . ", " . $avgs[2];
			$this->Variables['loadavg0'] = $avgs[0];
			$this->Variables['loadavg1'] = $avgs[1];
			$this->Variables['loadavg2'] = $avgs[2];
			$this->Variables['onlineusers'] = $this->MageBB->State->Output['onlineusers'];
			$this->Variables['onlineguests'] = $this->MageBB->State->Output['onlineguests'];
			$this->Variables['onlinemembers'] = $this->MageBB->State->Output['onlinemembers'];
			$this->Variables['loggedin'] = ($this->MageBB->Users->LoggedIn()?"true":"false");
			
			$menuNum = 1; // For dynamic menu items
			$this->Blocks['menuitems'][0]['link'] = "index.php";
			$this->Blocks['menuitems'][0]['title'] = "Home";
			if( !$this->MageBB->Users->LoggedIn() && $this->MageBB->Settings->AllSettings['allow_registration']) {
				$this->Blocks['menuitems'][$menuNum]['link'] = "register.php";
				$this->Blocks['menuitems'][$menuNum]['title'] = "Register";
				$menuNum++;
			}
			if( $this->MageBB->Users->LoggedIn() ) {
				$this->Blocks['menuitems'][$menuNum]['link'] = "accountcenter.php";
				$this->Blocks['menuitems'][$menuNum]['title'] = "Account Center";
				$menuNum++;
			}
			if( $this->MageBB->Settings->AllSettings['enable_memberlist'] && ($this->MageBB->Users->LoggedIn() || $this->MageBB->Settings->AllSettings['guestview_memberlist'])) {
				$this->Blocks['menuitems'][$menuNum]['link'] = "register.php";
				$this->Blocks['menuitems'][$menuNum]['title'] = "Member Listing";
				$menuNum++;
			}
			$this->Blocks['breadcrumbs'][0]['link'] = "index.php";
			$this->Blocks['breadcrumbs'][0]['title'] = $this->Variables['boardtitle'];
			$this->Blocks['breadcrumbs'][0]['post'] = "";
		}
		
		/**
		* Change or set a variable's value for the specific page
		*
		* @param	string	name
		* @param	string	value
		**/
		public function setVariable($name, $value) {
			$this->Variables[$name] = $value;
		}
		
		/**
		* Change or set a block's array value for the specific page
		*
		* @param	string	name
		* @param	array	values
		**/
		public function setBlock($name, $values) {
			$this->Blocks[$name] = $values;
		}
		
		/**
		* Add a block item to a specified block for the specific page
		*
		* @param	string	name
		* @param	array	values
		**/
		public function addBlockItem($name, $values) {
			$this->Blocks[$name][] = $values;
		}
		
		/**
		* Parse the $sysvar (Straight from PHP) variables in templates, contain generic data
		*
		* @param	string	toParse
		* @param	bool	failToFalse
		**/
		private function parseSystemVariables($toParse, $failToFalse=false) {
			// System Variable parsing
			preg_match_all('/\$sysvar\{(.*?)\}/i', $toParse, $varMatches);
			$replaceme = array();
			$replacements = array();
			foreach($varMatches[1] As $key => $matchName) {
				$InFail = str_replace("$","",$matchName);
				if(isset($$matchName))
					{ $replaceme[$key] = $varMatches[0][$key]; $replacements[$key] = $$matchName; }
				else if(isset($$InFail))
					{ $replaceme[$key] = $varMatches[0][$key]; $replacements[$key] = $$InFail; }
				else if(function_exists($matchName))
					{ $replaceme[$key] = $varMatches[0][$key]; $replacements[$key] = $matchName(); }
				else
					{ $replaceme[$key] = $varMatches[0][$key]; if(!$failToFalse) { $replacements[$key] = "Style error: ".$varMatches[0][$key]." is undefined."; } else { $replacements[$key] = "false"; } }
			}
			return str_replace($replaceme, $replacements, $toParse);
		}
		
		/**
		* Parse the $mbbsetting variables in templates, contain generic data
		*
		* @param	string	toParse
		* @param	bool	failToFalse
		**/
		private function parseTemplateIncludes($toParse, $failToFalse=false) {
			// String template replacements
			preg_match_all('/\$template\{(.*?)\}/i', $toParse, $varMatches);
			$replaceme = array();
			$replacements = array();
			foreach($varMatches[1] As $key => $matchName) {
				$replaceme[$key] = $varMatches[0][$key];
				$replacements[$key] = $this->outputTemplate($matchName, true);
			}
			return str_replace($replaceme, $replacements, $this->parseSystemVariables($toParse, $failToFalse));
		}
		
		/**
		* Parse the $mbbsetting variables in templates, contain generic data
		*
		* @param	string	toParse
		* @param	bool	failToFalse
		**/
		private function parseSettingVariables($toParse, $failToFalse=false) {
			// String template replacements
			preg_match_all('/\$mbbsetting\{(.*?)\}/i', $toParse, $varMatches);
			$replaceme = array();
			$replacements = array();
			foreach($varMatches[1] As $key => $matchName) {
				if(isset($this->MageBB->Settings->AllSettings[$matchName]))
					{ $replaceme[$key] = $varMatches[0][$key]; $replacements[$key] = $this->MageBB->Settings->AllSettings[$matchName]; }
				else
					{ $replaceme[$key] = $varMatches[0][$key];if(!$failToFalse) { $replacements[$key] = "Style error: ".$varMatches[0][$key]." is undefined."; } else { $replacements[$key] = "false"; } }
			}
			return str_replace($replaceme, $replacements, $this->parseTemplateIncludes($toParse, $failToFalse));
		}
		
		/**
		* Parse the $magebb variables in templates, contain generic data
		*
		* @param	string	toParse
		* @param	bool	failToFalse
		**/
		private function parseVariables($toParse, $failToFalse=false) {
			// String template replacements
			preg_match_all('/\$magebb\{(.*?)\}/i', $toParse, $varMatches);
			$replaceme = array();
			$replacements = array();
			foreach($varMatches[1] As $key => $matchName) {
				if(isset($this->Variables[$matchName]))
					{ $replaceme[$key] = $varMatches[0][$key]; $replacements[$key] = $this->Variables[$matchName]; }
				else if(strpos($matchName, "[") !== false) {
					preg_match("/(.*?)\[(.*?)\]$/", $matchName, $matches);
					if(isset($this->Variables[$matches[1]][$matches[2]]))
					{ $replaceme[$key] = $varMatches[0][$key]; $replacements[$key] = $this->Variables[$matches[1]][$matches[2]]; }
					else
					{ $replaceme[$key] = $varMatches[0][$key];if(!$failToFalse) { $replacements[$key] = "Style error: ".$varMatches[0][$key]." is undefined."; } else { $replacements[$key] = "false"; } }
				}
				else
					{ $replaceme[$key] = $varMatches[0][$key];if(!$failToFalse) { $replacements[$key] = "Style error: ".$varMatches[0][$key]." is undefined."; } else { $replacements[$key] = "false"; } }
			}
			return str_replace($replaceme, $replacements, $this->parseSettingVariables($toParse, $failToFalse));
		}
		
		/**
		* Parse simple ($coutput{CONDITION?ONTRUE?ONFALSE}) conditional statements
		*
		* @param	string	toParse
		**/
		private function simpleConditional($toParse) {
			// Conditional template replacements
			preg_match_all('/\$coutput\{(.*?)\?(.*?)\?(.*?)\}/si', $toParse, $varMatches);
			$replaceme = array();
			$replacements = array();
			foreach($varMatches[1] As $key => $matchName) {
				$evalMe = $this->parseVariables($varMatches[1][$key], true);
				if(eval("if(".$evalMe.") { return true; } else { return false; }"))
					{ $replaceme[$key] = $varMatches[0][$key]; $replacements[$key] = $varMatches[2][$key]; }
				else
					{ $replaceme[$key] = $varMatches[0][$key]; $replacements[$key] = $varMatches[3][$key]; }
			}
			return str_replace($replaceme, $replacements, $toParse);
		}
		
		/**
		* Parse full $if{condition} dowhatever $else dowhatever $endif conditional statements
		*
		* @param	string	toParse
		**/
		private function fullConditional($toParse) {
			// Conditional template replacements
			preg_match_all('/\$if\{\"(.*?)\"\}(.*?)(|\$else(.*?))\$endif/si', $toParse, $varMatches);
			$replaceme = array();
			$replacements = array();
			foreach($varMatches[1] As $key => $matchName) {
				$evalMe = $this->parseVariables($varMatches[1][$key], true);
				if(eval("if(".$evalMe.") { return true; } else { return false; }"))
					{ $replaceme[$key] = $varMatches[0][$key]; $replacements[$key] = $varMatches[2][$key]; }
				else
					{ $replaceme[$key] = $varMatches[0][$key]; $replacements[$key] = $varMatches[4][$key]; }
			}
			return str_replace($replaceme, $replacements, $toParse);
		}
		
		private function ParseBlocks($toParse) {
			preg_match_all('/\$openBlock\{(.*?)\}(.*)\$closeBlock\{(.*?)\}/si', $toParse, $blockMatches);
			if(count($blockMatches[0]) < 1) return $toParse;
			foreach($blockMatches[1] As $key => $matchName) {
				if(isset($this->Blocks[$matchName])) {
					$replacementHTML = "";
					preg_match_all('/\$blockItem\{(.*?)\}/i', $blockMatches[2][$key], $itemMatches);
					foreach($this->Blocks[$matchName] As $block) {
						$replaceme = array();
						$replacements = array();
						foreach($itemMatches[1] As $itemKey => $itemMatchName) {
							if(isset($block[$itemMatchName]))
								{ $replaceme[$itemKey] = $itemMatches[0][$itemKey]; $replacements[$itemKey] = $block[$itemMatchName]; }
							else
								{ $replaceme[$itemKey] = $itemMatches[0][$itemKey]; $replacements[$itemKey] = "Style error: ".$itemMatches[0][$itemKey]." is undefined in block ".$matchName."."; }
						}
						$replacementHTML .= str_replace($replaceme, $replacements, $blockMatches[2][$key]);
					}
					$toParse = str_replace($blockMatches[0], $replacementHTML, $toParse);
				} else { $toParse = str_replace($blockMatches[0][$key], "Style error: Block '".$matchName."' is undefined.", $toParse); }
			}
			return $toParse;
		}
		
		/**
		* Parse the style's template
		*
		* @param	string	templateName
		*
		* @returns	string	Parsed Template Contents
		**/
		private function parseTemplate($templateName) {
			// Read file
			$templateContents = file_get_contents(ROOT . "styles/" . $this->StyleData['FolderName'] . "/" . $this->Templates[$templateName]['FileName']);
			$templateContents = $this->simpleConditional($templateContents);
			$templateContents = $this->fullConditional($templateContents);
			$templateContents = $this->parseVariables($templateContents);
			$templateContents = $this->parseBlocks($templateContents);
			return $templateContents;
		}
		
		/**
		* Output template with appropriate finalisation
		*
		* @param	string	templateName
		**/
		public function outputTemplate($templateName, $return=false) {
			// 01/06/2008, Rudi - Added finalisation
			if(!isset($this->Templates[$templateName])) {
				if($return)
					return "Style error: Template $templateName does not exist.";
				echo "Style error: Template $templateName does not exist.";
				return;
			}
			$parsed = $this->parseTemplate($templateName);
			if((boolean)$this->MageBB->Settings->AllSettings['compress_style'] == true) {
				/* Note: This will work as long as there are no preformatted paragraphs as whitespace such as tabs are
						stripped. Add note to theme developer guide. */
				$working = $parsed;
				// Strip tabs
				$working = str_replace("\t", "", $working);
				// Strip double spaces
				$working = str_replace("  ", "", $working);
				// Strip empty lines
				$working = preg_replace("@(^[\r\n]*|[\r\n]+)[\s\t]*[\r\n]+@", "\n", $working);
				// Put closing tags together working from MAX_LINE_EMPTY_TAGS
				preg_match_all("@(</.*>[\r\n]*){1,".MAX_LINE_EMPTY_TAGS."}@", $working, $matches);
				$working = str_replace($matches[0], preg_replace("@[\r\n]*@", "", $matches[0]), $working);
				// Put tag-only lines together working from MAX_LINE_EMPTY_TAGS
				preg_match_all("@(<.*>[\r\n]*){1,".MAX_LINE_EMPTY_TAGS."}@", $working, $matches);
				$working = str_replace($matches[0], preg_replace("@[\r\n]*@", "", $matches[0]), $working);
				$finalTemplate = $working;
			} else $finalTemplate = $parsed;
			if($return) return $finalTemplate;
			else echo $finalTemplate;
		}
	}
	
?>


Example "templates" below:
Using Blocks:
<div id="menu">
$openBlock{menuitems}
	<a href="$blockItem{link}">$blockItem{title}</a>
$closeBlock{menuitems}
</div>

Example usiong pretty much everything, $if{}, $coutput{}, etc.
$if{"$magebb{loadavg0} > $mbbsetting{max_load}"}
	<div id="badnotice_tl">
		High Server Load Detected
	</div>
$endif
<div id="mainBody">
	<div id="header">
		<img src="$magebb{imagedir}magebb_logo.png" alt="$magebb{boardtitle}'s Logo" id="logo" />
		<div id="right">
			$template{menu}
			$if{"$magebb{loggedin}"}
				Logged in
			$else
				$coutput{$mbbsetting{usejs}?
					<a href="" id="showlogin" class="smalltext">Show Login Form</a>
					<div id="loginform">
				?}
					<form action="login.php" method="post" class="smalltext">
						Username: <input type="text" name="username" />
						Password: <input type="password" name="password" /> <input type="submit" name="submit_dologin" value="Login" />
						$coutput{$mbbsetting{usejs}?[<a href="" id="hidelogin">Hide</a>]?}
					</form>
				$coutput{$mbbsetting{usejs}?</div>?}
			$endif
		</div>
		<div style="clear:both"></div>
	</div>
	<div id="maincontent">
		$template{breadcrumbs}

This post has been edited by MageUK: 09 June 2009 - 03:32 PM

Was This Post Helpful? 0
  • +
  • -

#11 ShaneK  Icon User is offline

  • require_once("brain.php"); //Fatal error :/
  • member icon

Reputation: 239
  • View blog
  • Posts: 1,224
  • Joined: 10-May 09

Re: Templates o.o

Posted 09 June 2009 - 04:14 PM

Thanks for your help y'all, I think I'm gonna get into Smarty. It seems pretty nice...

Yours,
Shane~
Was This Post Helpful? 0
  • +
  • -

#12 AdaHacker  Icon User is offline

  • Resident Curmudgeon

Reputation: 452
  • View blog
  • Posts: 811
  • Joined: 17-June 08

Re: Templates o.o

Posted 09 June 2009 - 04:21 PM

View PostCTphpnwb, on 9 Jun, 2009 - 03:52 PM, said:

The thought of searching through pages of that to alter something makes me shudder. I'd much rather go through well-written OOP.

What do you mean by "well-written OOP"? Are you referring to putting HTML markup directly in your class methods?

It would be interesting to see an example of what you're talking about. No offense intended, but I have a hard time imagining what you could be doing that wouldn't make the code harder to maintain. This type of template is pretty much standard. It provides all the functionality you need in a template system (because it's all built into PHP anyway), it can be reused in different parts of the application, and it allows for a sharp separation between business logic and presentation logic. I'd be very interested in hearing exactly what you think is wrong with it and what you think would be better.
Was This Post Helpful? 0
  • +
  • -

#13 CTphpnwb  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 2834
  • View blog
  • Posts: 9,737
  • Joined: 08-August 08

Re: Templates o.o

Posted 09 June 2009 - 04:51 PM

Well, I just did a tutorial on creating dynamic drop downs that I'd like to get your opinion about. I did it as function and the idea was that it could be made part of a class. With a little work it could be more generalized to allow more than one set of dynamic drop downs. Lots of html in that!

I don't think there's anything wrong with a template necessarily, but I have a hard time with the idea that the designer shouldn't be expected to know or at least understand OOP. That, and adding a CSS file, an include or two, and a framework/template in order to make things easier seems to always add to the confusion instead. People get lost trying to figure out where things are.

On the other hand, if I put some html in a method it's there for a reason, and I can usually see the reason right away. Maybe it's because I'm the only one working on my own code though. Still, I think most people here are able to follow things I write without much difficulty. ;)


Edit:
I think that my basic approach is that an object may contain some business logic (I hate that phrase!) but most of the real decision making is done in the controlling code. Here's an example that seems to scale well for me:
<?php 
class rectangle {
	var $width;
	var $length;
	var $color = "Blue";
	
	function area() {
		$this->thearea = $this->width * $this->length;
	}
	function perimeter() {
		$this->perimeter = 2*$this->width + 2*$this->length;
	}
	function output_stats(){
		echo "Length: ".$this->length." Width: ".$this->width."<br>Area: ".$this->thearea." Perimeter: ".$this->perimeter;
	}
}
session_start();
if(isset($_SESSION['box'])) {
	$box = $_SESSION['box'];
	$box->width++;
} else {
	$box = new rectangle;
	$box->width = 4;
	$box->length = 10;
}
$box->area();
$box->perimeter();
$box->output_stats();

$_SESSION['box'] = $box;
?>

The business logic is primarily after session_start(), and the object exists to do that logic's bidding, whether it be to calculate a value or output it. That's why it seems strange to me to look for a way to separate them. They're already separate!

This post has been edited by CTphpnwb: 09 June 2009 - 06:18 PM

Was This Post Helpful? 0
  • +
  • -

#14 AdaHacker  Icon User is offline

  • Resident Curmudgeon

Reputation: 452
  • View blog
  • Posts: 811
  • Joined: 17-June 08

Re: Templates o.o

Posted 10 June 2009 - 07:54 AM

Interesting. There's a lot to talk about here.

View PostCTphpnwb, on 9 Jun, 2009 - 05:51 PM, said:

...I have a hard time with the idea that the designer shouldn't be expected to know or at least understand OOP.

Are you talking about web designers here, as opposed to developers? If so, then I think you're just flat-out wrong. There's a reason the two job titles are separate - different skill sets and responsibilities. It's not the designer's job to be messing with back-end classes and they shouldn't be expected to understand them. In fact, the entire reason we even have things like Smarty is that many groups don't want the designers writing PHP code at all, let alone modifying classes.

Quote

That, and adding a CSS file, an include or two, and a framework/template in order to make things easier seems to always add to the confusion instead. People get lost trying to figure out where things are.

Well, you're certainly right that adding layers of abstraction makes the code harder to follow on the initial reading. If you're looking at an unfamiliar codebase, a straight-forward approach is much easier to follow. But that's not the point. The goal should be long-term maintainability, not making things easy for new programmers. In my experience, adding abstractions and separating concerns gains you more in the long run than it costs in ramp-up time for new developers.

Quote

That's why it seems strange to me to look for a way to separate them. They're already separate!

Well...sort of. As you descibe it, you have indeed separated the "business logic" from the display logic. However, you've instead coupled the display code with your domain object, which, while different, really isn't any better.

Actually, it's funny you should use the rectangle example. On "Uncle Bob" Martin's page on the SOLID principles, the link for the Single Responsibility Principle uses this exact same example. Basically, a class - particular a domain object - should have a distinct purpose, i.e. one reason to change. The rectangle class doesn't really need to know how to display itself. There are any number of ways you might want to display the rectangle data, depending on the context. Having to change the rectangle class every time you want to try a new way becomes unmaintainable in the long run. It's better to just delegate that responsibility completely.

Quote

Well, I just did a tutorial on creating dynamic drop downs that I'd like to get your opinion about.

I have a few thoughts/suggestions on that. I don't mean to be critical - I think it's great that you're contributing to the community - it's just that I would have done it very differently.

First, one thing that really bothers me is all the strings of HTML and Javascript code. Just drop out of PHP mode, for crying out loud! I don't mean to single you out, but I've noticed that a disturbing number of people in this forum like to echo out HTML code from PHP. Maybe it's a personal preference thing, but this just drives me crazy. My biggest gripe is that it defeats tool support. Any good code editor or IDE will do syntax highlighting (and maybe even intellisense and code completion) for HTML and Javascript code in PHP files if they're outside the <?php ?> blocks. With code in strings...not so much. Also, I just find it harder to read, what with having to worry about escaping quotes and concatenation and whatnot.

Moving on to more substantive issues, I don't necessarily have any problem with encapsulating all of this in a function call if your intention is for people to use it as a drop-in menu component. That can be a useful technique in certain circumstances. However, I don't really see how what you have is any different than a simple template. All you're doing is echoing out a bunch of code and doing a little processing to massage the input into the format you want - which isn't really necessary because it could just as easily be made the responsibility of the caller. It's just doing the same thing with different syntax. And as far as making this a class method goes, absent any context, it's not at all clear to me why you'd want to do that.

What's more, I really don't think there's any need to do this in PHP at all. There's nothing here that really needs to be done on the server-side, so I don't see why you couldn't do the whole thing in straight Javascript. Instead of using PHP to generate a bunch of Javascript arrays, it seems to me you could just as easily have passed in a Javascript object literal as your input. Not only would the code be clearer, but it would also be usable from any server-side language, because the caller just needs to generate JSON. In fact, this kind of smells like the sort of thing you'd write a jQuery plugin for.
Was This Post Helpful? 1
  • +
  • -

#15 CTphpnwb  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 2834
  • View blog
  • Posts: 9,737
  • Joined: 08-August 08

Re: Templates o.o

Posted 10 June 2009 - 08:53 AM

View PostAdaHacker, on 10 Jun, 2009 - 10:54 AM, said:

Quote

...I have a hard time with the idea that the designer shouldn't be expected to know or at least understand OOP.

Are you talking about web designers here, as opposed to developers? If so, then I think you're just flat-out wrong. There's a reason the two job titles are separate - different skill sets and responsibilities. It's not the designer's job to be messing with back-end classes and they shouldn't be expected to understand them. In fact, the entire reason we even have things like Smarty is that many groups don't want the designers writing PHP code at all, let alone modifying classes.

Yes and no. I wouldn't expect a web designer to modify the back-end methods, but I would expect them to be able to modify a class method that contained html output. If you really wanted to keep them separate, you could have class_two extends class_one and one class has the output and the other the business logic. No need to go any further.

Quote

That's why it seems strange to me to look for a way to separate them. They're already separate!

View PostAdaHacker, on 10 Jun, 2009 - 10:54 AM, said:

Well...sort of. As you descibe it, you have indeed separated the "business logic" from the display logic. However, you've instead coupled the display code with your domain object, which, while different, really isn't any better.

I think it's better because it's simpler, and it achieves the same goal without adding overhead.


Quote

Well, I just did a tutorial on creating dynamic drop downs that I'd like to get your opinion about.

View PostAdaHacker, on 10 Jun, 2009 - 10:54 AM, said:

I have a few thoughts/suggestions on that. I don't mean to be critical - I think it's great that you're contributing to the community - it's just that I would have done it very differently.

Well, it is more to demonstrate the concept than anything else. I'd want to generalize it a bit more before adding it to a class. It would be good to be able to have more control over divs and values/options, etc.

View PostAdaHacker, on 10 Jun, 2009 - 10:54 AM, said:

First, one thing that really bothers me is all the strings of HTML and Javascript code. Just drop out of PHP mode, for crying out loud! I don't mean to single you out, but I've noticed that a disturbing number of people in this forum like to echo out HTML code from PHP. Maybe it's a personal preference thing, but this just drives me crazy.

It's definitely a preference thing. I learned to program before there was html, and when I see people break out/in of/to php it makes my skin crawl. To me, html is just data like any other. You echo/print it to a device, which then does what it does with it. It isn't code in the sense of a program, at least until it gets to the client side, so treating it like code just adds to the confusion. While an editor can help, just looking at that makes my eyes glaze over.

View PostAdaHacker, on 10 Jun, 2009 - 10:54 AM, said:

What's more, I really don't think there's any need to do this in PHP at all. There's nothing here that really needs to be done on the server-side, so I don't see why you couldn't do the whole thing in straight Javascript. Instead of using PHP to generate a bunch of Javascript arrays, it seems to me you could just as easily have passed in a Javascript object literal as your input.

I did it using php because I saw people asking how to do it in php. Also, I'm not as good in javascript, probably because I tend to view javascript as a necessary evil with its inherent insecurity and browser compatibility issues. I'll look into it though!
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1