A Question About Embedding HTML In PHP - php

Some time ago I read a posting on a board where the person was talking poorly about people that have HTML embedded/within their PHP. I do quite a bit of PHP development but I still interleave HTML and PHP in the same document. Is there a better way to do this, am I doing it wrong? I know that in JSP/JSF they use an XML document with namespaces to insert their HTML code so I was wondering if there was a similar function that PHP uses that I should be taking advantage of.
Thanks for taking the time to read. :-)

PHP was originally designed as a templatng language. It sort of evolved over time to give it more power, but that doesn't mean you can't still use it for templating. A few <?=$var?>s here an there isn't too awful; hardly worse than {{var}} or whatever other syntax these new fangled engines offer.
The thing you really should do though, is take as much "business logic" out of the "views" as possible. That means the only code on the display page should be stuff that's actually relevant to how the page looks. No database updates or stuff like that. If you do this, then it should have nice, clean, maintainable pages :) No framework or anything necessary.
That said, I'd only do this for smaller apps. Template engines don't hurt either ;) Especially if your designer is a non-programmer.

Yes. You could separate the presentation code into different files. They call them views, or templates. There are a pretty bunch of templating engines you could use: there's smarty, there's Twig, and a lot of others.
You could also use a full-featured framework, like Zend, Symfony, CakePHP, Code Igniter etc. There's a lot of lists floating around.
Best regards,
T.

You should consider using a template engine such as Smarty instead of mixing logic and presentation. This clears up both code and page, and forces you to define your requirements for the page clearly before invoking the template engine.

Related

Embedding php and html

Ok, it might be a banal question but i'm a little bit confused.
I'm going to develop a project by my own. This means i'll build the HTML template, the PHP scripts, MYSQL query, AJAX calls and CSS styles.
This means no other people will touch any part of the code.
I know templates are good ways to make the entire application easy to be modified. But is that so necessary to do it? Since i'm the only one who got to know what that files and what that page do?
Using common patterns in the development of software products is not only about making it more readable/maintainable but also about making it extensible. The longer your software will be in use, the more features will be requested/desired. Extending one big mess of a software will not work out in this case.
Try a php framework (e.g. Zend Framework / Symfony(1/2)), there are lots of tutorials which allow you an easy start with or without templating engine (I use twig atm, which does a great job!).
If i were you, i wouldn't use templates (do you mean PHP frameworks?) but thats just me.
You don't have to use a template engine - PHP itself can do that just fine.
In general, it's a good idea to "separate concerns" (eg. code which outputs HTML is separate from code which loads data from the database) - it improves the readability and organization of code, making it easier to maintain and faster to develop further.
You should have a look at a framework, like symfony. Most frameworks make use of MVC and hence provide a good separation of your code.
But is that so necessary to do it? Since i'm the only one who got to know what that files and what that page do?
Yes, if you want to keep it maintainable in the long run. If you are not constantly working on the code, you will forget how some things work eventually and then you are happy if you have a proper separation and organization.

Template language vs. straight PHP

I'm going to write a CMS, but right now I'm writing down all my ideas and trying to get all of my concepts straight before I start. One of the things I'm torn on is whether to use a template language and parse the pages of the website, and replace template tags with content items, or just develop the site with straight PHP and have the CMS generate data structures which help. For example:
{navigation: products}
vs.
foreach($cms_label['products'] as $product) {
echo '<li class="product_nav">'.
'{$product.name}'.
"</li>\n";
}
The former is cleaner but it would involve inventing a language, plus parsing every page before display. The latter is less clean but I think it could work really great if the CMS just provided data for all the code. But, would this be considered mixing logic with presentation? Another alternative I've considered is using PHP functions that are similar to the template tags:
<?php navigation('products'); ?>
What are your thoughts?
Keep in mind I don't have to do anything more complicated than including a page at a certain place, or writing out an unordered list; the rest shall be handled by CSS.
Template languages for PHP are an example of an anti-pattern called "Inner-Platform Effect." Smarty is an example of a template framework for PHP, but even Hasin Hayder, author of a book on Smarty says that Smarty is dead and there's no need to use it anymore.
There can be good reasons to develop a template language, for example if you are having non-coder designers or content editors using your CMS and you don't want to overwhelm them with the complexity of PHP (or allow them to write code that could break your website).
But you haven't described that as a goal, so I'd assume using PHP as your page template language is best in this case. It'll be less work because you don't have to develop your own new language, and it'll provide greater flexibility for uncommon cases where you need a specific kind of dynamic content.
Don't write PHP functions to encapsulate blocks of HTML output. Instead, use include() to pull in fragments of HTML. This technique is sometimes called "partials."
You can also use an MVC framework such as Symfony, Kohana, Solar, CodeIgniter, or Zend Framework to help you keep discipline about separating your PHP template code from the rest of your application code.
I was a very happy Smarty user for a long time, I don't believe in specialized template languages any more.
A template language won't prevent you from putting inappropriate logic in your presentation code, it'll just force you to write bad code in the template language.
It's fairly trivial to roll your own little template system that uses php in the templates. Then create various helpers to keep your template code clean (like your "navigation()" function).
I think the approach taken by Zend_View is pretty good. Symfony's view-layer stuff is fairly neat too, but might be a little intimidating. You don't have to use a framework to get something from it. Just look at some of the template code in the examples, and see what inspires you.
Bottom line: forget about a special language for templates -- just apply good design sense to your view code, factoring complexity out of the view scripts and into reusable helpers.
Reinventing the wheel is most of the time a bad idea.
PHP is already a templating language. You don't need to implement your own.
As for Smarty it is the most complete templating system for php and it is still a bad idea.
A couple of articles on the subject:
Once upon a time there was Smarty! by Hasin Hayder. He actually wrote a book on smarty and he doesn't recommend it.
Php and Templates by Harry Fuecks (Author of the 1st edition of the php Anthology)
If you want to look at templates done better look at:
phpSavant it uses php code and still promotes separation of concerns.
The final objective is of course to have easier code to maintain by promoting separation of Business Logic and Presentation
You might want to look into Smarty- http://smarty.php.net Smarty is a very powerful template engine that gives you the best of both worlds. It has extensive support for custom modules and plugins.
I built a custom CMS with Smarty and PHP and have nothing but good things to say about it.
The php code to use Smarty looks like this
<?php
// my cms
$smarty = new Smarty();
.
.
$smarty->display('home.tpl');
?>
The template code is something like this
<h1>{$pagetitle}</h1>
{insert tag="navigation"}
I wonder why noone mentioned what is one of the most important uses of a template language: automatic output escaping.
It's easy to forget a htmlspecialchars() here or there, so a template language that provides directives like {$name} has to make sure $name is automatically passed through htmlspecialchars, with the appropriate charset and everything.
Of course, that also implies that you can specify a different "context" for variable output, such as e.g. alert('Hi {$name|context=singlequotes}!'); where the template interpreter would escape $name's content so that it is impossible to break out of the single quotes, instead of XML escaping it (which should be the default).
Such contexts can also include stuff like int (to force a number), and it can also be extended to accept additional parameters to format the output, et etc.
My 2 cents. Not sure if there's an open source solution that allows for this (would be interested to hear about it!), I rolled my own interpreter for this stuff at work. Since the resulting "intermediate code" is pure PHP, it can also very easily be "cached" (like Smarty and other tpl systems do).
I pretty much like Smarty and I also think controllers should be purely written in XML and models in YAML. This is the only way to enforce MVC.
If the question of performance arises only then compilation to php might be considered as a possibility (albeit a remote one) with the sine qua non condition that it's done in an obfuscated fashion, to thwart eager developers from reading it.

PHP: Separating Business logic and Presentational logic, is it worth it? [duplicate]

This question already has answers here:
Closed 13 years ago.
Possible Duplicate:
Why should I use templating system in PHP?
I was just curious as to how many developers actually do this?
Up to this time I haven't and I was just curious to whether it really helps make things look cleaner and easier to follow. I've heard using template engines like Smarty help out, but I've also heard the opposite. That they just create unnecessary overhead and it's essentially like learning a new language.
Does anyone here have experience with templates? What are your feelings on them? Are the helpful on big projects or just a waste of time?
On a side note: The company I work for doesn't have a designer, there are just two developers working on this project charged with the re-design/upgrade. I also use a bit of AJAX, would this have issues with a template engine?
Not only does this practice make the code look cleaner, it also has many long term and short term benefits.
You can never go wrong with organizing code. First off it makes it much easier to maintain and easier to read if someone else has to pick up after you. I have worked with Smarty before and it is nice, it keeps the designers work from interfering with the program code.
Using template systems and frameworks would make it much easier to accomplish tasks. There is a rule of thumb you can follow which is DRY (Don't Repeat Yourself). Frameworks help you achieve this goal.
You may want to look into MVC, this is the model that these frameworks are based off of. But you could implement this design structure without necessarily using framework. Avoiding the learning curve. For frameworks like Zend, the learning curve is much greater than some other ones.
I have found that Code Igniter is fairly easy to use and they have some VERY helpful video tutorials on their website.
Best of Luck!!
Actually it's the business logic that needs to be separated from the views. You can use php as a "template language" inside the views.
You can use ajax on any template engine i think.
Edit
My original response addressed the question whether to use a template engine or not to generate your html.
I argued that php is good enough for template tasks, as long as you separate business logic from presentation logic.
It's worth doing this even for simple pages, because it enables you to:
isolate the code that is the brain of your application from the code that is the face, and so you can change the face, without messing with the brain, or you can enhance the brain without braking the looks
isolate 80% of bugs in 20% of your code
create reusable components: you could assign different presentation code to the same business code, and vice versa;
separate concerns of the feature requests (business code) from the concerns of the design requests (presentation code), which also usually are related to different people on the client side, and different people on the contractor side
use different people to write the business code and the presentation code; you can have the designer to handle directly the presentation code, with minimal php knoledge;
A simple solution, which mimics MVC and doesn't use objects could be:
use a single controller php file, which receives all requests via a .httpdaccess file;
the controller decides what business and presentation code to use, depending on the request
the controller then uses an include statement to include the business php file
the business code does it's magic, and then includes the presentation php file
PHP is a template engine (or if you prefer, a hypertext preprocessor). When HTML is mixed heavily with PHP logic, it does become very difficult to maintain, which is why you would have functions defined separately to build various parts and simply build the page from short function calls embedded in the HTML. Done like this, I don't see much of a difference between Smarty and raw PHP, other than the choice of delimiters.
Separation of concerns is a very important tenant to any type of software development, even on the web. Too many times I have found that people just throw everything into as few files as possible and call it a day. This is most certainly the wrong way to do it. As has been mentioned, it will help with maintainability of the code for others, but more than that, it helps you be able to read the code. When everything is separated out, you can think about easily.
Code Ignitor, I have found, has been the easiest to learn framework for working with PHP. I pretty much started my current job and was up and running with it within a few days, from never having heard of it, to using it pretty efficiently. I don't see it as another language at all, either. Basically, using the framework forces me to organize things in a manageable way, and the added functionality is anlagous to using plugins and such for jQuery, or importing packages in Java. The thought that it's like learning another language seems almost silly.
So, in short, organize organize organize. Keep in mind, though, that there is a level of abstraction that just becomes absurd. A rule of thumb is that a class (or file in our case) should do one thing very well. This doesn't mean it is a class that wraps around print, but takes a string, formats it using a complex algorithm and then prints it (this is just an example). Each class should do something specific, and you can do that without any framework. What makes MVC great, though, is that it lets you organize things further, not just on the single class level, but on the level of "packages", being Model, View, and Controller (at least in the case of these frameworks; there are other ways to package projects). So, now you have single classes that do things well, and then you have them grouped with similar classes that do other things well. This way, everything is kept very clean an manageable.
The last level to think about once you have things organized into classes, and then packages, is how these classes get accessed between packages. When using MVC, the access usually will go Model<->Controller<->View, thus separating the model (which is usually database stuff and "business" code in the PHP world), from the view (which usually takes information from the user, and passes it along to the controller, who will then get more information from the model, if necessary, or do something else with the input information). The controller kind of works like the switchboard between the two other packages usually. Again, there are other ways to go with packaging and such, but this is a common way.
I hope that helps.
Smarty and other php template frameworks really do nothing more than compile to PHP anyway, and they also cache their results in most cases to allow for faster processing. You can do this all on your own, but if you ever look at the compiled templates that Smarty generates, and compare to the original Smarty template you create, you can see that one is far more readable than the other.
I write mostly mod_perl these days and started using templates (HTML::Template) halfway through our ongoing project. If I had to make the decision again, I would use templates right from the start - rewriting later to use templates is kind of tedious, though rewarding because you get nicer and cleaner code. For anything bigger than 2-3 pages in php, I would also use some template engine.
One big advantage of a templating engine such as Smarty is that non-developers can use it to embed the necessary logic that is used on the front-end (one really can't separate logic and display on all but the simplest sites). However, if the developer is the one maintaining the pages then using PHP would be preferable in my opinion.
If you separate out large logic blocks and maintain a consistent patten for looping and for-each flow control statements (i.e. don't use print statements, or only use print statements for one-liners, etc.) Then that should be okay.

how to use Smarty better with PHP?

I found that using Smarty with PHP, sometimes extra time will need to be used for
1) using quite different syntax than PHP itself
2) need to check small cases, because documentation doesn't give finer details, such as for "escape"
http://www.smarty.net/manual/en/language.modifier.escape.php
it doesn't say escape:"quotes" is for double quotes only or for single quotes as well, so you need to write code to test it. Also for the case of escape:"javascript" -- can't tell exactly what and how it is escaped.
3) for something complicated, need to write helper functions or modifiers, so it needs a creation of new files and ending up doing it in PHP again.
by the way, does using Smarty provide a good speed up over use PHP alone? thanks.
First, PHP is a templating language. Keep that in mind when you talk about using a template system for your PHP-based web applications.
The only 'real' argument that I've ever heard for using ANY templating engine was that they provide a simpler language for template manipulation which can be handy if you have template designers who don't know PHP and whom you don't trust to learn to use PHP judiciously.
Regarding these arguments, I would argue that if your template designers are not competent to learn enough PHP for template design, you should probably consider finding new template designers. Additionally, PHP itself provides a different syntax for control statements that you might use in a template versus in code. For example:
<? foreach($array as $key => $val): ?>
<?= $val ?>
<? endforeach; ?>
VS:
<?php
foreach($array as $key => $val) {
echo $val;
}
?>
Personally, I believe that templating engines arose in PHP because:
That's way that other languages do it
Better PHP programmers realized that they needed a way to enforce separation between presentation and application logic and templates were an easy way to do this.
The first reason is just kinda silly. The second reason can be overcome with a little self-control and even a rudimentary understanding of the necessity of separating layers in an application. The MVC design pattern is one way of approaching this problem. As far as exercising some self-control, my rule is that only necessary loops and if statements get used as well as functions that filter, escape, format the output for the screen.
Having used Smarty extensively, I can honestly say that it always presented me with more hurdles to get over than it did solutions. If anything, switching to PHP-based templates is what has actually decreased development time for both templates and code.
I don't like templating engines. I find them very lossy and resource-intensive for PHP.
With MediaWiki, around version 1.6.x we backed off using Smarty by default and just use PHP's built-in templating, with a great improvement in performance.
I've found that most of what people want to do with a templating system (add links, change colors, remove text or sections of the page) are better done with a simple system of event hooks.
Laconica, the open microblogging platform, doesn't do any templating by default. We have a plugin for people who are crazy for templating.
Smarty is certainly one of the best template engines out there. In my experience though people would be well advised to think their use cases through more thoroughly before they use any templating engine on top of PHP at all.
First, PHP itself is perfect for templates. Pretty much the only justification for using another templating engine is if you're allowing untrusted users to create or edit templates, since they could execute all kinds of badness. So, if your project has user-editable templates, use Smarty. If not, stick with PHP.
If your problem is separation of code and layout, I suggest you look into implementing a lightweight MVC-style execution model. Or, to put it more condescendingly, if you have deeper logic code in your template, it's probably time to do some refactoring.
Performance is another consideration. Yes, rendering a Smarty template comes with a cost. But after it's done, the output should be cached, leading you to improved execution times. Same goes for PHP templates. PHP allows you to implement all kinds of granular caching models through the use of its output buffers. But beware of premature optimization: do that only after you're code complete and have identified what the actual bottlenecks are!
The biggest cost when using Smarty or any other engine comes in the form of developer time. It's another layer of complexity and inevitably you will find yourself in situations where you have to trick the engine into doing what you could have accomplished within pure PHP all along.
I like template engines and think they should be used, but in the particular case of Smarty, I think it's waste of time, because it's not a significant improvement over PHP as templating language:
The new syntax is still based around old concept of special tags inserted in random places in the document.
Because Smarty does not understand HTML's syntax/structure, it cannot not help you to create valid/well-formed HTML. Smarty's tags violate HTML's syntax, so once you add them, other standard tools can't help you either.
Smarty's output, just like in PHP, is insecure (unescaped) by default and you have to remember to add |escape everywhere where you output data in HTML.
There's one particular PHP template engine that I've fallen in love with, which fixes all those problems: PHPTAL.
It's still something new you have to learn, and it's a depenency for your application, but I think having XSS and ill-formedness problems solved makes it worth the trouble.
PHPTAL just like Smarty is compiled once to PHP and cached, so performance is comparable to raw PHP.
Pros
No PHP in your HTML files (Allows both PHP and HTML identing)
Pipes {$var|default:"None selected"} {$var|urlencode}
Foreachelse: {foreach item=row from=$results}{$row.name}<br>{foreachelse}No results{/foreach}
Themable websites/pages (Using only CSS has it limits)
Cons
Other language syntax
Not always obvious code {"Y-m-d"|strftime:$timestamp} {$array|#var_dump}
Slight overhead
I can highly recommend the "template" approach(mVc), but both Smarty and plain PHP are up for the task.
As far as I know Smarty is one of the best template engines speed wise. Maybe it takes a while to get used to it. But if you are not working on the system alone and the amount of html and style files is huge it speeds up the development significantly.
While working on my last project the design was changes a couple of times but logics was the same. I guess that's the best example when Smarty or any other template engine helps a lot.
Personally I use Blitz for templating. On the site the author claims it is the fastest templating engine and provides a (biased?) chart over performance between different templating systems for PHP. I haven't used smarty myself, but this may give you some hints on its performance.
http://alexeyrybak.com/blitz/blitz_en.html
Using Smarty as a templating engine will probably not be as performant as not using it, as it is an extra layer of software, i.e., a templating language on top of a, erm, another templating language. On the other hand, if you use the caching feature properly you could realise overall performance gains.
Smarty templates are pre-compiled before being output to the browser, which involves writing temporary files to disk. This step surely penalises performance, at least a little.
If you are confident in your ability to keep implementation and presentation separate, and have no real interest in server-side caching, you should probably just use pure php templating. Some MVC frameworks such as Zend Framework have their own PHP-like templating systems.
On the other hand, smarty is a decent way to enforce a neat separation of presentation from implementation, particularly where it's unclear as to what belongs where. It might help discipline you to enforce this necessary separation.
That said, I use Smarty in most of my PHP projects, as it reminds me of Java-Server Tag Libraries (JSTL), which I'm very, very used to, and fond of.
Using a Smarty or not is more or less a philosophical position.
I use it, although I don't use much functionality. Using it this way, templates tend to be be very simple. Pass an associative array with parameters, iterate through its components and insert required elements in the result page. This keeps templates clean and (hopefully) free of business logic.
Additionally, extending Smarty is quite simple.
As an example, I added a styles parameter to the fetch() to have a fetchUsingStyle(). This allows me to switch between different layouts of a site quite easily.
Furthermore, my fetchUsingStyle() searches various locations for a template: First tries to find the current style. If not found, it tries to load the template using a default style. Last, it tries to locate a pure static dummy file, a placeholder for something to be implemented later.
Try to Use Smarty with MVC pattern such as Codeigniter , Its better than core PHP
Why use a template engine when you can just use your html files and inject php code where you need it? you can do this with Psttt! templating engine for php
full source code here http://github.com/givanz/psttt

PHP best design practices

Ok, have a bunch of questions that I have been thinking about the past few days. Currently I have a site that is just a bunch of PHP files with MySQL statements mixed in with PHP, HTML and CSS, basically a huge mess. I have been tasked with cleaning up the site and have made for myself, the following requirements:
The site needs to be efficient and well laid out (the source code), I would like to be able to write as little code as possible.
There has to be good separation between structure, presentation and logic.
For whatever reason, I can't use a framework and need to keep the code maintainable and "simple" as there will be future developers working with it.
There needs to be an admin section for at least a few pages.
Saying that, this is what I know about the site as it is now:
Consists of 10-12 pages, a few are completely static, most are dynamically driven via a database and there is a huge form for users to fill out (20-30 fields) that need to be validated and checked.
The hierarchy of the site is basically 5-6 main pages and then sub-pages within those.
So, knowing those things I wanted to know if anyone had any tips/suggestions as to how to go about doing this with the least amount of headaches.
Would an OO approach be best in this situation?
Since there are many static pages and the dynamic pages just need the content filled in would it be best to use some kind of basic template?
EDIT: Thanks for the answers, when I said no frameworks I basically meant anything that would require new syntax other than PHP, as whoever gets hired to work on this site after me will probably only know PHP.
Here's an article about how to organize your PHP project, from Rasmus Lerdorf, the architect who created the language:
http://toys.lerdorf.com/archives/38-The-no-framework-PHP-MVC-framework.html
Despite the popularity of OO frameworks for PHP, Rasmus advocates a less OO approach. He knows more than anyone about PHP intended usage, and how to take advantage of its architecture for high-performance websites.
edit: In response to the comment by #theman, I'll concede the article isn't a fine work of writing, but I think the content is important. Using PHP as it was intended to be used is better than struggling against its weaknesses to make it fit an OO mold.
I highly recommend the Smarty templating engine for all PHP projects. It gives you an easy way to separate the logic from the presentation.
Have a look at this SO question and the answer. It's a pretty good, simple MVC design with some tips on how it can be improved. If you are concerned about maintenance, then at the very least you need to seperate presentation from logic (you need a view and controller). Smarty forces that, but it is a type of framework and you'll have additional syntax to learn.
Before you jump on Rasmus' "no framework php mvc framework" bandwagon, read some of the critical comments. Any web application structure is a framework, and Rasmus' approach isn't the best I've seen.

Categories