Template Engine

Not for 'how-to' coding questions but PHP theory instead, this forum is here for those of us who wish to learn about design aspects of programming with PHP.

Moderator: General Moderators

alex.barylski
DevNet Evangelist
Posts: 6267
Joined: Tue Dec 21, 2004 5:00 pm
Location: Winnipeg

Post by alex.barylski »

patrikG wrote:
Hockey wrote:Your arguments are valid, but out of context amigo.


Oles arguments are perfectly on topic, contrary to what you are offering, hockey. You are mostly directly engaging with Ole as a person, not with the arguments he put forward.
Hockey wrote:Yes, we should adapt to new methodologies and make better use of our time, agreed. But we also shouldn't use something based on the fact some one told us that it's the cats meow, until you fully understand what it is it's offering. Thats called naievty I think.
There are estimates that 80% of development time is nowadays used for maintenance, 20% for creating code from scratch. Point is: if the code had been written for humans first and computers second, there would be more time to innovate.
Hardware is dirt-cheap, will get even faster, smaller and with more capacity and bandwidth. Good developers won't get faster, won't get cheaper (on the contrary), won't get smaller and their capacity will cap at some point.

On a meta-level: tone down statements that can be interpreted personal attacks, hockey.
No personal attacks intended...I apologize if they came out that way Ole.
You are mostly directly engaging with Ole as a person, not with the arguments he put forward.
I'm stubborn to realize my own faults I guess, but your gonna have to point out where I made this faux pas???

Cheers :)
User avatar
Weirdan
Moderator
Posts: 5978
Joined: Mon Nov 03, 2003 6:13 pm
Location: Odessa, Ukraine

Post by Weirdan »

won't get smaller
hmm... debateable :lol:
User avatar
Ollie Saunders
DevNet Master
Posts: 3179
Joined: Tue May 24, 2005 6:01 pm
Location: UK

Post by Ollie Saunders »

[personal]
No personal attacks intended...I apologize if they came out that way Ole.
Whilst I appreicate patrik is looking out for the community I don't think your comment was personal. Just the usual Hockey stuff I expected :)
I'm stubborn to realize my own faults I guess, but your gonna have to point out where I made this faux pas???
Indeed you are. Many great people were very subborn but that is because they had big ideas that other people didn't get.

I have a suggestion to make to you. We are getting personal here but this is only advice. I'm not trying to prove how clever I am (I do that way to much here and I'm beginning to realize how much it <span style='color:blue' title='I'm naughty, are you naughty?'>smurf</span>-s people off) but it might benefit you in life as a whole. Anyway here is the suggestion:

Think about the justifications you have for your opinions. Take a comment you have said to justify something you believe in and then try to think of all the possibe arguments somebody else could use against it. How many of those arguments do you have answer for? Its like having a debate with yourself. If you find you don't know enough to complete the debate do some research otherwise you will be able to come to a solid conclusion. What is more you will know exactly what to say to someone who argues with you, very powerful indeed! If someone does argue with you about that point you have self-debated over and says something you hadn't thought of BE RECEPTIVE! Its really easy to get angry with someone who prooves that a way of thinking you have had for a long time was wrong. But the fact is that person has just done you a massive favour, you have learnt something new and improved yourself as a result. Finally, assess the credibility of the person you are talking to, some people just aren't worth the bother.
[/personal]
Performance will be an important issue until computers are completely automated...yes it's less and less so every year, but why add bloat when you don't need too???
Thats just naive and bad programming practice IMHO. Why not just have random LOOPs inside your code:

Code: Select all

for($i=0; $i<10000; $i++);
Well I wasn't suggesting that.
I wrote:we should take the easiest, most flexible/adapatable path
adding extra code so slow it down isn't included :) but what is included is reducing repetition and redunancy both of which have the side-effect of improving performance. In short, what I am saying is, good, refactored, code will have resonable performance to start with before you do any kind of profiling and optimization.

I'd also like to say at this point I attended another PHPLondon pubcon today (even better than last time) and there was a presentation on XDebug and kCacheGrind (profiling) and one of the slides in that reiterated many of the points I made in my last post. There are many presentations about preformance online here and I like these here. There was one particular one I remember where guy talks about a web app he wrote and how it will require 50 servers to run it for the number of people that will use it and he manages to get it down to 1 but I can't find it. You will notice that they all, without exception, use profiling to establish where the bottlenecks are.
Smarty, although in theory sounds awesome, in pragmatic terms it's nothing more than a glorified version of native PHP template engine, doing nothing but eating clock cycles and chewing RAM by the mega byte.
Have you actually tried it or made any attempt to learn it? If you find it has no use for you that is perfectly acceptable, or if you aren't interested in the idea enough to investigate that is too. But you can't just slate something to hell without understanding exactly what you are slating.
alex.barylski
DevNet Evangelist
Posts: 6267
Joined: Tue Dec 21, 2004 5:00 pm
Location: Winnipeg

Post by alex.barylski »

Whilst I appreicate patrik is looking out for the community I don't think your comment was personal. Just the usual Hockey stuff I expected
Oh thanks :P :lol:

Whats that supposed to mean? :D
Indeed you are. Many great people were very subborn but that is because they had big ideas that other people didn't get.
Now your implying i'm great? :P You too man...your fantastic :)

Not sure about big ideas...but people certainly don't understand me most of the time thats for sure. :roll:
Think about the justifications you have for your opinions. Take a comment you have said to justify something you believe in and then try to think of all the possibe arguments somebody else could use against it.
I do that all the time...by virtue of the fact I confess when I'm wrong, doesn't that imply I have considered both sides of a answer, decided on one, then later felt the other argument was correct so I switched opinions...

It's like battling with arborint about design patterns...I never seen a purpose in formalizing my understanding of the subject as they are basically practices and principles I have learned through osmosis over the years of development. But after much consideration I thought "meh" I'll read about the more common ones and what what 30 different people all preeching the same practice have to say might possibly persuade me. I can see the benefits.

iamsure convinced me over time of the importance behind xhtml validation, web accessibility and standards. At first I argued because it didn't seem economical to make the switch. Learning to write XHTML when every client I have ever had has never even mentioned it, didn't seem to make $$$ sense. But after some consideration and battling with myself, I decided he was right, so I dove into learning about web accessibility. Slowly but surely I'll get there, but for now it's enough to be convinced of it's importance and at least make a honest effort on future projects.

In this case though, I can't see myself stepping down as no one has provided any tangible reasons as to why Smarty should be used over PHP's native templating funcitonality.

Smarty adds un-nessecary bloat, when the same functionality can be easy emulated (chicken and the egg) using plain vanilla PHP. Perhaps you are unaware of PHP's inbuilt templating syntax??? :roll:

Code: Select all

//
// class.tplengine.php
class PHP_Template{
  function fetch($tpl_file)
  {
     //$tpl = $this; // proivide differnt this pointer name for templates???
     // @extract($this->m_vars);  // Smarty assign instead of expando properties     

     ob_start();
     include($tpl_file);
     $buff = ob_get_contents();
     ob_end_clean();

     return $buff; // Return PHP template
  }
}
The template syntax can be very similar to that of Smarty's using PHP's alternative syntax

Code: Select all

<!-- test_template.tpl.php -->
<html>
  <head>
    <title><?php echo $this->title; ?></title>
  </head>
<body>
<?php for($i=0; $i<10; $i++): ?>
  <b>Test</b><br />
<?php endfor; ?>

<b>Author:</b> @AUTHOR@
</body>
</html>
Now you instantiate the PHP template object:

Code: Select all

include 'class.tplengine.php'; // Include the template engine
$obj = new  PHP_Template;

//
// TODO: Implement custom advanced (useful) caching here if needed

//
// We could emulate Smarty's assign very easily, but this looks nicer...
$obj->title = 'Some title pulled from DB, etc';

$buff = $obj->fetch('test_template.tpl.php ');

// TODO: Perform some pre-rendering filters on templates
$buff = str_replace('@AUTHOR@', 'Hockey Knows Best', $buff);

echo $buff;
References to support my claim:
http://www.phppatterns.com/docs/design/ ... te_engines
http://www.massassi.com/php/articles/template_engines/

The above is a *very* trivial, I assume not very well known method of using PHP's built-in templating services *without* the over head of learning a new snytax or keeping another library up to date, etc.

It's fast, there is ZERO compilation and it's more extendable/flexible due to the fact it's entirely done in PHP, so your not limited to obscure keywords like Smarty's {section}

The *only* advantage I can see Smarty offering is the fact you can actually disable PHP in the templates, which may come in handy when you have anonymous users posting templates. If I recall correctly, template lite doesn't have that option eneabled by default where as Smarty does. We had a huge disscussion about whether this was a security flaw or not. I think the general census was that it was *not* a security flaw. So you be the judge as to how important it is.

Without that, Smarty doesn't hold a candle to PHP inbuilt templating...sorry...but your arguments don't hold up to the truth.

Your Argument: Smarty offers modifiers?

My Answer: Sure does. It's flawed though. Why would I want my designers to have exclusive control over how my dates are formatted? Date formatting is a setting typically set in locale section of your web site (admin panel, etc) Therefore it requires some kind of logic control in setting the date format.

You could hack around this and use a Smarty config file and perhaps have smarty use the config variable, but I'm not sure if thats even valid syntax. Not only that, but what if I don't want to store template modifier parameters in a Smarty config? What if I want all my admin options in a DB???

Second approach, you could really hack Smarty and pull those admin options from a DB and format the value in your PHP code...but in that case, you've circumvented a problem by hacking *against* a system which is supposed to help you. When you could have just stuck with PHP and been done with. :P

Your Argument: Smarty has a powerful recirsive template inclusion facility

My Answer: You can do the same using PHP. But it's bad practice!!! Why, again, would I want to let my designers have exlcusive control over when a particular template should be used?

What if the templates are designed in such a way, that one has a login FORM and the other has a user menu???

These 2 layouts would likely then have to duplicate template code inorder to fulfill these 2 requirements.

Code: Select all

<!-- Login Template: login.tpl -->
<form>
  <input type="text" name="user" />
  <input type="password" name="pass" />
</form>

<!-- User menu: user_menu.tpl -->
<ul>
  <li>My Profile</li>
  <li>My Bookmarks</li>
  <li>My History</li>
  <li>My Account Stats</li>
</ul>

<!-- 
2 templates may possibly be required one to include login.tpl and another to include user_menu.tpl.

Not sure how else you solve this in Smarty, but doing it this way causes duplicate code...
-->
<html>
  <head>
    <title>{$title;}</title>
  </head>
  <body>
    <table>
      <!-- Left hand side navigation -->
      <td>
         {include file="login.tpl"}
         {include file="user_menu.tpl"}
      </td>
      
      <!-- Main document body -->
      <td width="100%">
         Some primary body content
      </td>
    </table>
  </body>
</html>
By quickly scanning over the documentation for {include}

http://www.phpfreaks.com/smarty_manual/ ... clude.html

i can see they have solved this issue noted above using variable interpolation techniques, like a PHP string.

You would basically inside your controller logic, need to determine which page content template is to be displayed and set the name of the template in a variable and assign that variable to the Smarty object.

Ok, so that fixes the problem, but it's still a *hack* and it's slower than just doing the following, especially when you use straight PHP.

Code: Select all

$smarty->assign('test', 'This will be injected into my body template');

switch($_GET['page'){
  case 'about':
    $buff = $smarty->fetch('about.tpl'); // Pull the about us page
    break;
  case 'faq':
    $buff = $smarty->fetch('faq.tpl'); // Pull the FAQ
    break;
  default:
    $buff = $smarty->fetch('default.tpl'); // Pull the default
    break;
}

//
// Assign layout title 
$smarty->assign('title', 'Hockey knows best');
$smarty->assign('body', $buff); // Inject body buffer into layout template
$buff = $smarty->fetch('layout.tpl');
Same effect, more control and less *unessential* Smarty hacks...

The above method is just as easy to implement in the PHP template version and doesn't incur the Smarty costs...

Your Argument: Smarty offers built-in compilation and caching

My Answer: Yes it does. However Smarty templates are essentially compiled into the PHP version I have shown you above at the start.

I'll explain the compilation/caching process as how I understand it :P

You write a template file using Smarty syntax...you have several templates most of which are likely body content templates and one or more layout (navigation, etc) templates.

The body/content templates are injected or included (recursively I'm willing to bet) into the primary layout template. I like to distinguish the two as Frame and View from my MFC programming days :P

Templates all sit in a directory you tell smarty to lookup as well as a cache directory and compile directory.

When you first run your code, Smarty finds each invoked template file and performs a psuedo-compilation on the template, basically converting it to it's PHP equivelant (again, what I've shown you above). The Smarty system, the actually calls that PHP file and using the technique I have shown above, includes the PHP based template and lets PHP perform it's parsing magic and execution.

So really, what I've shown you above as a PHP template engine, makes this comppliation step redundant, wouldn't you agree???

Redundancy, as you clearly understand as you inform me of good programming practice, etc...generally frowns upon code redundancy...it's bad practice these experts claim... :P

Anyways, after the compliation has completed...Smarty like I already said, actually includes the PHP version NOT the Smarty version...letting PHP do it's job...

However, here's the amazing part everyone loves so much...

Smarty, either using output buffering or catching the fetch() return value before returning (i'm not sure) actually takes a snapshot of the generated web page and stores it in the cache directory.

Isn't that amazing??? :wink:

Now, here is where I am unclear how Smarty works as after I came to these conclusions, I switched from Smarty to PHP templating...

But, experience would suggest...Smarty requires you to hardwire caching using it's API...

An API which lets you know whether a cache exists or not...

Code: Select all

include('smarty.class.php');
$smarty = new Smarty;

$smarty->setCacheDir('./mytemplates/');

$page = $_GET['page'];
if($smarty->isCached("$page.tpl"))
 echo $smarty->fetchCache();
else{
  //
  // All that page selection code I've shown previously
  //
}
That caching functionality is so basic...I could emulate it in minutes by customizing my PHP template class above.

What would be handy, is an event caching system. Where you could cache results of a threaded message forum and whenever someone posted or removed a message, then that page and others affected by change would inform the caching system to flush it's contents and start generating new ones...

So long as most visitors did nothing but read forum topics, this caching works like a charm and is actually worth talking about...

Most people don't spend time on static pages...like About Us, etc...they goto the dynamic sections which are difficult to cache or require customized caching services like I explained above...
Have you actually tried it or made any attempt to learn it? If you find it has no use for you that is perfectly acceptable, or if you aren't interested in the idea enough to investigate that is too. But you can't just slate something to hell without understanding exactly what you are slating.
I've written many differnt template engines, all experimental...but each using a different technique than the other. I have one of particular interest, which i'm sitting on...considering patent application as it uses quite a complex concept to solve many templating issues of current generation template engines ;)

I may be off in my understanding of Smarty...if I am...please by all means...inform me...open my eyes to a world I clearly do not understand... :)

Cheers :)
User avatar
RobertGonzalez
Site Administrator
Posts: 14293
Joined: Tue Sep 09, 2003 6:04 pm
Location: Fremont, CA, USA

Post by RobertGonzalez »

Ok, there was no way in crap that I was going to read all of that... :D

The fact is that many developers lean on tools that make their jobs easier. I use TemplateLite becuase it is fast, reliable, easy to use and easy to walk a web designer through if they are handling the front end while I take care of the back end. I also like the use of template parsers because, in my opinion, they allow for faster extensibility of theme switching. Plus I enjoy not throwing HTML into my code and vice versa.

Smarty is bloated. But it is still fast for smaller scale applications. TemplateLite is very fast and very lite. Given the choice of the two, I will always lean toward TL instead of Smarty. This is part preference and part operational judgement. But of all the parsers I have seen, TL and Smarty offer the most in terms of design side configuration and TL offers the lesser amount of resource usage.
alex.barylski
DevNet Evangelist
Posts: 6267
Joined: Tue Dec 21, 2004 5:00 pm
Location: Winnipeg

Post by alex.barylski »

Everah wrote:Ok, there was no way in crap that I was going to read all of that... :D

The fact is that many developers lean on tools that make their jobs easier. I use TemplateLite becuase it is fast, reliable, easy to use and easy to walk a web designer through if they are handling the front end while I take care of the back end. I also like the use of template parsers because, in my opinion, they allow for faster extensibility of theme switching. Plus I enjoy not throwing HTML into my code and vice versa.

Smarty is bloated. But it is still fast for smaller scale applications. TemplateLite is very fast and very lite. Given the choice of the two, I will always lean toward TL instead of Smarty. This is part preference and part operational judgement. But of all the parsers I have seen, TL and Smarty offer the most in terms of design side configuration and TL offers the lesser amount of resource usage.
Dude...you have to read it to understand what I was getting at...

I realize it's long...but after the last message I received from ole it was clear he misunderstood me completely...

I am *not* advocading template systems are wrong...I dunno how many times I have to say that...I'm just saying Smarty and similar (yes that includes TL) are not worth their weight for what they offer.

TL has even less argument IMHO as it's default state of allowing PHP to execute hinders it's stance in offering something useful.

Cheers :)
User avatar
RobertGonzalez
Site Administrator
Posts: 14293
Joined: Tue Sep 09, 2003 6:04 pm
Location: Fremont, CA, USA

Post by RobertGonzalez »

That whole issue of TL not being secure because of parsable PHP allowance has been done so I am not going to rehash that one. I will say that there are some good ones (that actually parse data) and there are some not so good ones. Then there are some that are just PHP code used to act like a template parser (like Savant). Whatever the case, template engines that add value and are secure, are good template engines, in my opinion.

As Forrest Gump said 'That's all I have to say about that'.
alex.barylski
DevNet Evangelist
Posts: 6267
Joined: Tue Dec 21, 2004 5:00 pm
Location: Winnipeg

Post by alex.barylski »

Everah wrote:That whole issue of TL not being secure because of parsable PHP allowance has been done so I am not going to rehash that one. I will say that there are some good ones (that actually parse data) and there are some not so good ones. Then there are some that are just PHP code used to act like a template parser (like Savant). Whatever the case, template engines that add value and are secure, are good template engines, in my opinion.

As Forrest Gump said 'That's all I have to say about that'.
Savant is basically what I"ve shown above but slimmed down...bTemplate is where I started from.

They all add value...I agree...however some (Smarty) also take back from that value...2 steps forward one step back... :P

It's a pointless performance hit when there are other ways of doing the exact same thing, but cleaner, faster and less muck in your app...
User avatar
Ollie Saunders
DevNet Master
Posts: 3179
Joined: Tue May 24, 2005 6:01 pm
Location: UK

Post by Ollie Saunders »

Clearly Hockey, you are very well informed. I accept your argument (I read most of it).

I'm still not entirely sure on Smarty myself but then i've never tried or written a template system. I've only once used Zend_View (very simple probably quite similar to TL) which seemed fine, I don't see myself needing anything more sohisticated yet.
alex.barylski
DevNet Evangelist
Posts: 6267
Joined: Tue Dec 21, 2004 5:00 pm
Location: Winnipeg

Post by alex.barylski »

ole wrote:Clearly Hockey, you are very well informed. I accept your argument (I read most of it).

I'm still not entirely sure on Smarty myself but then i've never tried or written a template system. I've only once used Zend_View (very simple probably quite similar to TL) which seemed fine, I don't see myself needing anything more sohisticated yet.
Zend_View from what I can tell actually uses the straight PHP approach as I've demonstrated...

It takes advantage of expando properties which IMHO is cleaner than using assign()

Assign() would handy if you needed to perform some kind of processing on each input before disply in the template

But I think that's where __set() and __get() come in even more handier...as I believe they allow default processing of member variables.

Cheers :)
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Post by John Cartwright »

I knew I shouldn't have made the initial post against templates.. 8O

Back on topic please.
alex.barylski
DevNet Evangelist
Posts: 6267
Joined: Tue Dec 21, 2004 5:00 pm
Location: Winnipeg

Post by alex.barylski »

Off topic sure...but many threads do that...

Why does what I said...make you wish you had not instigated such a debate?

What is it about what I said here (or any other post where I get remarks this) that makes you shiver with feelings of regret?

I haven't insulted anyone...I don't think...it was only moderately off topic...and IMHO offers detailed perspective as to how and why Smarty might not be an ideal candidate for templating...

So i'm curious...where did I go wrong? :?
User avatar
Ollie Saunders
DevNet Master
Posts: 3179
Joined: Tue May 24, 2005 6:01 pm
Location: UK

Re: Template Engine

Post by Ollie Saunders »

So i'm curious...where did I go wrong?
I thought the topic had been answered.
Roja wrote:
anthony88guy wrote:I've never used a Template Engine for my projects but I've worked with some. I'm interested in working with Smarty, but is it possible with a shared host?
Absolutely.
anthony88guy wrote:If you view the Smarty quick install guide it looks like you need shell access?
No, they just use that as the example because its easier to show what to do. You can also ftp the files into a shared host, and access them that way. There is no need for shell access.
User avatar
mikealeonetti
Forum Newbie
Posts: 5
Joined: Wed Sep 06, 2006 2:52 pm
Location: Long Island

Post by mikealeonetti »

I apologize for taking this topic even more off... topic, but I never replied and I feel bad.
Hockey wrote:Smarty doesn't support array loops???
No, when I tried it months ago I tried to embed two loops. What I did was, I got a multi-dimensional array. 'Cause, Smarty only lets me loop with arrays as far as I know. There is no way to recall templates to loop them. So, I had to make a multi-dimensional array for my menu system with sub menus.

What I'd do with PHP code:

Code: Select all

foreach( $menu_items as $item )
{
  print( "{$item['text']}<br>" );
  foreach( $item['submenu'] as $sub_item )
  {
    print( "--{$item['text']}<br>" );
  }
}
And I tried to do something similar with Smarty, but it wouldn't let me. I spent a lot of time searching google for "multidimensional arrays smarty" but I found only plugins.

So, that's why I made my own template. A template that would allow looping in the templates as well as looping HTML outside of them. And one that allowed and embedding of any tags infinitely. Since it makes them all into PHP code it runs smoothly. The way variables are set and kept makes this possible also.

Not advertising, just saying that's the course I had to take. Flexibility is one of my favorite things.
User avatar
RobertGonzalez
Site Administrator
Posts: 14293
Joined: Tue Sep 09, 2003 6:04 pm
Location: Fremont, CA, USA

Post by RobertGonzalez »

Smarty handled nested loops just fine (at least TL does it with no problem). You loop the same way in the template as in the code.

Code: Select all

	{foreach key=di value=div from=$divisions}
	<div class="relatedLinks"> 
		<h3>{ $div } Division</h3>
		<ul>
	{section name=ti loop=$teams}
		{if $teams[ti].team_division == $di}
			<li><a href="{$u_teams}/{ $teams[ti].team_domain_short }/" title="Get more information on the { $teams[ti].team_name }">{ $teams[ti].team_name }</a></li>
		{/if}
	{/section}
		</ul>
	</div>
	{/foreach}
Post Reply