I've been looking for some guidelines on how to layout PHP code. I've found some good references, such as the following:
http://www.dagbladet.no/development/phpcodingstandard/
and this question on SO.
However, none of that quite gets to what I'm specifically wondering about, which is the integration of HTML and PHP. For example:
Is it OK to have a PHP file that starts out with HTML tags and only has PHP inserted where needed? Or should you just have one section of PHP code that contains everything?
If you have a chunk of PHP code in the middle of which is a set of echo's that just output a fixed bit of HTML, is it better to break out of PHP and just put in the HTML directly?
Should functions all be defined in dedicated PHP files, or is it OK to define a bunch of functions at the top of a file and call them later on in that same file?
There are probably other questions I'd like to ask, but really I'm looking for someone to point me at some kind of resource online that offers guidance on the general idea of how HTML and PHP should be combined together.
Combining programming code and output data (including HTML) is IMHO a very bad idea. Most of the PHP gurus I know use a template engine such as Smarty to help keep the two things separate.
There's really not a single, common standard for these things. Most languages are more restrictive than PHP in this sense.
In the later years, a lot of so-called frameworks have emerged, and amongst other things they define a set of rules for everything from naming over where to place files and to which style your code should follow. There are several frameworks around, so you can't really pick one and call it the standard. However, most frameworks have a subset of commonality. For example, most follows some variant of the PEAR Coding Standards.
I usually try and follow the standards that are set by the language's core libraries.... oh wait.
Seriously through - you should try and follow the MVC pattern in any web application as it is pretty much standard practice regardless of language. In PHP this can be achieved in a quick-and-dirty way by treating index.php as your controller and separating data logic and presentation by file. This small step will at least let you move your code to a full featured framework when and if you choose.
Use a template engine when you can. If you haven't learned one, or don't want the overhead (which is minimal), use practices that cause you to have quick-and-dirty templating:
Functions that do not display anything have no place in a file that does display something.
Print variables, not HTML. Whenever outputting HTML, break out of the PHP and write HTML with print statements to handle any small details that are needed (actions for forms, IDs for controls, etc.).
Remember, when you include a file that breaks out of the PHP to print content, that will be treated the same as if you do it in the main file. So you can create simple templates that just included PHP files, and those files will print variables in the right places. Your index.php (or whatever) does all the real work, but all the display is done by the secondary "template".
Many PHP tutorials intermix logic and display code. It took me years to break the bad habits that encouraged in me. In my experience you can't separate things too much in PHP, and entropy will pull you towards intermixed code if you don't fight it.
Coding standards should be more than how to layout your syntax, but sadly that's what they tend to be in PHP.
FWIW, phc will pretty print your code in the Zend style.
Related
I know things like these have been asked and answered several times before, is it just that I can't grasp the idea easily or too hard to accept that things are really like this and that.
I know that HTML is used for Front-End where the tedious work is done in the Client, and PHP is working behind the scenes (Server-Side). With so many regulations, instruction, standards, so on and so forth.. I believed I have already confused myself with these stuffs, making things (new and old) hard for me to chew and understand especially when it comes to their best uses...
Anyway, I have created a web application based on the concept of MVC tho I didn't used the strong fundamentals of the topic nor a framework, I separated the Logic, Rules and Design concerns by my own.
Unfortunately, I wound up with some issues similar to which is the right way to do the things, how this should be implemented, etc...
I end up needing to template the HTML, however, since I've used HTML as HTML itself, I end up updating/editing each and every affected file (for. eg. a web page header), unlike when I used PHP before, literally a file with a .php extension, where I can fully utilize templating, however, i read somewhere that it is not a good practice because it breaks the HTML.. so which one should I follow and how can I solve my problem, should I move to .php and then create a template page, or is there a way I could do such with HTML? if there is any, how can it be done?
Please for the meantime, don't point me to frameworks available, I want to understand basic things first before studying frameworks...
Anyone, please...
Edit...
so this is just fine and that it doesn't have any drawbacks...
main.php
<?php php stuffs ?>
<html>
<body>
HTML stuffs and some <?php php stuffs ?>
</body>
</html>
HTML has no templating capability.
It has frames and iframes, but they come with significant drawbacks and only provide include functionality.
You should use a proper templating language. This can run on the client, server or build system.
I'd recommend against running it on the client. It adds an unnecessary dependency that your visitors (including search engine indexers) have to fulfil.
PHP will do the job (it straddles the border of being a programming language and a templating language). My personal preference is for Template-Toolkit.
TT can run in your build system via the ttree utility, or you can run it on your server. There is a tutorial covering how to build websites using it.
If, and when, you move to building websites with more demanding server side requirements, then you can continue to use TT as it is supported but most of the web frameworks in Perl land (e.g. the dancer module for TT and the catalyst module for TT. Note that those links go to the hardcode documentation for the modules, and if you plan to use one of the frameworks you should start with a higher level tutorial)
HTML is a markup language - in other words it can mark up text to display to the user.
It cannot do any of the dynamic type functions you might need in a web application - like updating the date, for example.
So it is best to think of HTML documents, just like you might think of a Word document, a load of text that is displayed to the user.
As soon as you want to start using templates to display dynamic information (stuff from a database, maybe), you're going to need a scripting language. PHP is good for this.
I've had good experience with Smarty - a php templating engine.
On a side note, learning a framework can be a really useful part of the learning the basics. Most frameworks force you to do things in a good way, and sometimes the things they make you write in your code may seem a bit strange or illogical, suddenly one day the penny will drop and you'll realise why what you've been forced to do is sound from an engineering point of view.
You can look # javascript templating. I suggest you to give a try to http://mustache.github.com/
Modest is a template system that's supposed to look and feel like HTML.
The most common way to do HTML templating with PHP, is to use one of these popular templating engines :
Smarty
Twig
Latte
Mustache
Alternatively, you can just put placeholders in your HTML that look something like <% variablename %>. Just load your HTML, do a regex do find all placeholders and replace them with the corresponding variables.
Alternatively, you can load your HTML, parse it as a DOM document and then modify your DOM. I created the library DOM Query to be able to do this with a jQuery-like syntax, but you could use vanilla PHP or one of several other libraries as well.
Alternatively, you can do some HTML templating in frontend with JavaScript. If you want to do HTML templating both on frontend and backend, you might want to consider using Mustache, because Mustache templates can be used both in frontend (with JavaScript) and in backend (with PHP).
I am looking at optimization options, and after checking SO questions, I don't quite see an answer for what I am trying to do. Hopefully that doesn't indicate that what I am doing is a bad practice!
I have an intranet application that loads page content via ajax calls to php files. A lot of the php files have a mixture of php, JavaScript, even some HTML, specific to the interface functionality that they load into the main interface. I was wondering about minifying or compressing these files. Is there a way to do it, or am I stuck because I have mixed languages?
Update: Concerning accepted answer:
I have accepted wildpeaks answer because I think it most closely answers my original question. However, this is one of those times when I wish I could accept two answers because I think the answer Igor Zinov'yev provided has given me perhaps a more important design decision to think about. For that reason I have given a +1 to his answer, as I imagine others will too. Hope that makes sense and is within the SO rules.
Your PHP script generates the Javascript code, so it can minify the code before outputting it: generate the code in a variable, then pass that variable to the minifier, and only then output to the browser.
Here's a PHP library for that.
You are starting your optimization off the wrong end. Obviously if you have hard-coded JavaScript, HTML and whatever else inside your PHP files, you seriously need to refactor the code. But even if you don't, you shouldn't minify the code in place because it would be even harder to maintain.
Pull it out of there, start with small steps, and you will get there eventually.
UPDATE: I thought of replying with a comment, but instead decided to elaborate on why I answered your question this way here.
I'm talking here about separation of concerns. Your server-side code files are no place for the client-side code. All solutions that do this that I have seen so far sooner or later turn into an unmaintainable mess.
If you want to return a piece of HTML code, put it into a template and supply the template with variables that are specific for this current situation. You can do that with Smarty. This way you get among others the following benefits:
No repeating pieces of markup over and over - there are template loops for that
A possibility to re-use existing templates in several places
Developers working with templates do not need to get into your server-side code
And your server-side code gets cleaner, smells nice too!
Later on when you separate logic from presentation maybe you will find that you don't need to send JavaScript code with HTML snippets. Maybe you will create a single JS engine (that you will minify on build) and will only have to trigger certain events upon load.
Lets say I have 2 cases:
<?php
print("html code goes here");
?>
v.s
<?php
?>
html codes goes here
<?php
?>
Would the performance for PHP interpreter in the first case be worse than the second one? (Due to the extra overhead of processing inside print function).
So, does anyone have a recommended way to insert html codes inside php codes?
Oh, for the sake of all those who edit your code later, please never put any significant amount HTML code inside a string and echo it out. In any language.
HTML belongs in HTML files, formatted and styled by your IDE or editor, so it can be read. Giant string blocks are the biggest cause of HTML errors I have ever seen.
Performance shouldn't matter too much, in this case, but I would assume the second would be faster, because it is streamed directly to the output or buffer.
If you want it to be easier to read, enable short tags, and write it like this:
?><b>blah blah blah</b><?
Plus, with short tags enabled, it's easier to echo out variables:
Hello, <?= $username ?>
If you are using this to generate some sort of reusable library, there are other options.
You should put HTML outside of PHP code in order for better maintenance and scalability. It's also very beneficial to do all your necessary data processing before displaying any data, in order to separate logic and presentation.
Rather then try to think about constantly separating your php and HTML you should instead be in the mind set of separating your backend logic and display logic.
The MVC pattern is a good way of thinking about your code - In order to correctly use PHP you must use MVC (model-view-controller) pattern
Never put HTML inside PHP codes unless you specifically intend to do so or its very small. But then again 100% separation is what i recommend. People will have to work very hard to understand your code later if you mix them up. Especially designers who may not be comfortable with php.
The golden rule is separation of the front and back end process to the maximum helps in every aspect. Keep things where they belong. Styles in CSS, Java-scripts in JS, Php in a library folder/files and just use the required classes/functions.
Use short tags <? if required (but i dont like it :P ) also <?= tag for output echo. Besides short tags are better be avoided.
Don't do it that way at all! Use a templating system like Smarty so you can separate your logic from your display code. It also allows you to bring in a designer that can work with html and might not know php at all. Smarty templates read more like HTML than PHP and that can make a big difference when dealing with a designer.
Also, you don't have to worry about your designer messing with your code while doing a find/replace!
Better yet would be to go to a setup like Django or Rails that has clearly delineated code/template setup, but if you can't do that (cheap hosting solutions) then at least use templating. I don't know if smarty is the best thing for PHP, but its far better than both solutions you are proposing.
[head above the parapet] Many of us have learnt templating from WordPress where without embedding php it's virtually impossible to do anything. I can quite understand why people advocate strict MVC or engines such as Smarty but the fact is in the case of WordPress development you need to manipulate output on the fly with php. In fact, coming from that background, I always use to assume that the 'hp' in php was for exactly that reason. So I could write 'normal' looking HTML, do a bit of server-side processing and then return to HTML.
So, from my point of view, the answer to your question, is the second of your examples is much easier to read - one of the fundamentals of elegant coding. But it does depend. If there's a lot of processing to produce a simple piece of html then it may be easier to build a large variable and echo it at the end. I abhore multiple lines of echo statements. In this case I am likely to use a function to keep my HMTL clean. Again WordPress does this a lot; for instance the_title() returns a simple string but does a deal of processing before returning this string so <h1><? the_title(); ?> </h1> reads well.
That is the POV of a WordPress developer who was never formally taught complex coding. I expect to lose a fair amount of reputation points over this answer. [/head above the parapet]
I learned PHP by hacking away at phpBB2, even submitting a few mods to their database, which others downloaded and used. (I don't believe phpBB2 is supported any more with phpBB3 out so long now, so the v2 mods database is no more.)
One of my favorite things about phpBB was their templates system, which let the editor completely separate the HTML and the PHP. PHP files contained PHP: logic, database queries, and activating the templates. TPL files contained templates: HTML, template variables, and specialized HTML comments to allow for conditional or repeating blocks.
However, any time I see someone's PHP code online, it's either a small snippet working with a single function or such, or the PHP is full of strings containing HTML (or worse, HTML with PHP interspersed). phpBB is the only PHP I've looked at which actually separates the language and the markup language, suggesting to me that few, if any, other PHP codebases do such a thing.
I'm looking to start working with some PHP again, but this time it won't be a phpBB forum, and it will be on a team. Based on my experience, separation of PHP and HTML is uncommon (please correct me if I'm wrong on this!). However, I'm so used to that dividing line, I hate reading mixed PHP and HTML.
In the "real world" of PHP programming, what's the preferred method:
PHP files with strings of HTML
HTML files broken up with PHP blocks
PHP and HTML completely separate (I wish?)
Something else?
If you want to separate the PHP from the HTML you can use a template engine (Like smarty http://www.smarty.net/).
Personally, I see no reason to add a template system/language into the mix, when PHP is already a prefectly good solution.
My preferred approach is to separate the display from the logic of the application. This could take the form of a full blown MVC framework. However, it could also be a simple matter of how you go about writing your code.
Expansion:
Ever since making the mistake of interspersing my HTML with copious amounts of ASP code, I have tried to separate page logic from display. Within a single page, this means placing all of the page logic at the top, storing the information to be displayed in variables and then echoing them out within the HTML at the bottom of the PHP file. The only logic which appears in the HTML portion is display logic. In other words, simple error handling, ifs, loops, etc. Basically, the same stuff that you'll find in most templating languages.
My reason for avoiding templating languages is that it's yet another form of syntax that I need to worry about. What's the point? PHP provides more than I need for this purpose.
Meanwhile, you can take a simple MVC approach by separating things:
controller.php
<?php
// some application logic
$data['message'] = 'Hello, World.';
include 'view.php';
exit;
?>
view.php:
<html>
<head>
<title>
A simple 'MVC' view
</title>
</head>
<body>
<p>
<?php
echo $data['message'];
?>
</p>
</body>
</html>
This isn't without its drawbacks and issues. However, if you think you can have complete, clean separation between application logic and display, you're mistaken.
We use a customized code igniter base for MVC and just have logic and layout separated. that doesn't necessarily mean there's no php in our html, just that its not used for logic. It's perfectly okay to loop through a recordset with php code in a template imho, just don't try to talk to business objects and actually do stuff in the layout templates. You could ofcourse also look into something like tal or a million others for the templates if you really want to get rid of all php code there. I'm kinda thinking that's mostly overkill though, unless "insert special circumstance here"
edit fixed typo
In my experience, a lot of PHP development, whether for better or worse, ends up being php files connected to each other through includes that print out snippets of HTML as needed.
Mind though, most of my PHP experience is for more of a "we just need something that works" solution than a "we need the most elegant and efficient solution"
any time I see someone's PHP code online, it's either a small snippet working with a single function or such, or the PHP is full of strings containing HTML (or worse, HTML with PHP interspersed).
Yeah, the general quality of code out there is embarrassing.
Whilst you can go to a full-blown templating engine of your own, that may be overkill and in many cases the limited domain-specific-languages they provide will get in your way, when you could just be writing presentation logic in PHP.
If you want to still be writing normal PHP, but without the spaghetti:
Keep action code at the top of the file or in a different file. Put only application logic here, not any kind of HTML or templating. Any information generated in this stage that needs to be displayed by the template needs to go in a variable to be passed to the templating part, not printed out in the middle of a load of business logic.
Take your knowledge of tag-based templating and apply it to PHP. Have a single, correctly-indented hierarchy of code for both HTML and PHP presentation logic, as if you were writing ‘well-formed’ XML (whether or not you're actually using XHTML). Avoid putting HTML in strings at all costs.
Define an easier way of calling htmlspecialchars(), because otherwise typing that all the time is going to be a real pain, and if you aren't typing it all the time you're going to have potentially security-sensitive errors.
To summarise, eg.:
<?php
// active code here
// do things
// put any errors in a $errors array
// this trivial function would presumably be in an include
//
function h($s) {
echo htmlspecialchars($s, ENT_QUOTES);
}
?>
<body>
<?php if (count($errors)!=0) { ?>
<ul id="errors">
<?php foreach ($errors as $error) { ?>
<?php h($error); ?>
<?php } ?>
</ul>
<?php } ?>
...
</body>
In the "real world" of PHP programming, what's the preferred method:
Oh, in the real world of PHP programming, the average project has a mishmash of approaches thrown together without any thought. In the real world the code is unmaintainable, bug-ridden, and insecure. You don't want to look at the Industry Standard, because the Industry Standard is to be broken in every way.
I prefer to use a template system to minimize the amount of PHP code contained in the HTML files. I really don't see any way to entirely separate PHP from HTML, but I feel that it is sufficient to separate business logic (database) from presentation logic.
My template system is home-baked, but I'm sure you can find a variety that would work by preforming a google search.
Based on my experience, separation of PHP and HTML is uncommon
True. But lot of PHP code is written by inexperienced developers. Further, PHP does not encourage, but rather discourage writing good code, and the ability to mix HTML with programming code is one of the examples of this.
If you expect to do high quality code, to be able to easily maintain and extend it, I highly recommend using template engine or something similar. Mixing both has a huge impact on the readability of your code, and will result in something becoming worse and worse over time. Refactoring will be painful, if not impossible.
Now, you have a large choice of the way to separate HTML from PHP
The most obvious one is to use an existing layout engine. There are plenty of them, some very well done and with a very low performance impact.
You can also write your own engine. It may not be a good idea on a big project (why reinvent the wheel?), but can be a solution either on a tiny project or when you need something very specific.
The last way I use in most projects is to build XML from business layer (XML serialization is quite easy in PHP), then to use XSLT to transform this to HTML page. It enables to do websites which are much easier to maintain and more easy to understand, and, by the way, enables to access the website data programmatically (loading XML instead of HTML page) when need. On the other hand, it decreases performance hugely, so is not intended for large websites with thousands of queries per second.
Most code starts with PHP and HTML strings, then evolves into a templating system during a big rewrite. Separating content from logic up front requires design, planning and communication among the team. Using XML or JSON instead of PHP arrays as the data format makes this easier.
you can mix up PHP inside HTML or vice versa simply by adding opening <?php and closing ?> PHP tags between your HTML.
<!DOCTYPE html>
<head>
<title>Hello world as text</title>
</head>
<body>
<?php
echo "<p>Hello world</p>";
?>
</body>
</html>
For more details : https://stackhowto.com/how-to-combine-html-and-php/
So I have seen some comments on various web sites, pages, and questions I have asked about separating php and html.
I assume this means doing this:
<?php
myPhpStuff();
?>
<html>
<?php
morePhpStuff();
?>
Rather than:
<?php
doPhpStuff();
echo '<html>';
?>
But why does this matter? Is it really important to do or is it a preference?
Also it seems like when I started using PHP doing something like breaking out of PHP in a while loop would cause errors. Perhaps this is not true anymore or never was.
I made a small example with this concept but to me it seems so messy:
<?php
$cookies = 100;
while($cookies > 0)
{
$cookies = $cookies -1;
?>
<b>Fatty has </b><?php echo $cookies; ?> <b>cookies left.</b><br>
<?php
}
?>
Are there instances when it is just better to have the HTML inside the PHP?
<?php
$cookies = 100;
while($cookies > 0)
{
$cookies = $cookies -1;
echo'<b>Fatty has </b> '.$cookies.' <b>cookies left.</b><br>';
}
?>
When people talk about separating PHP and HTML they are probably referring to the practice of separating a website's presentation from the code that is used to generate it.
For example, say you had a DVD rental website and on the homepage you showed a list of available DVDs. You need to do several things: get DVD data from a database, extract and/or format that data and maybe mix some data from several tables. format it for output, combine the DVD data with HTML to create the webpage the user is going to see in their browser.
It is good practice to separate the HTML generation from the rest of the code, this means you can easily change your HTML output (presentation) without having to change the business logic (the reading and manipulation of data). And the opposite is true, you can change your logic, or even your database, without having to change your HTML.
A common pattern for this is called MVC (model view controller).
You might also want to look at the Smarty library - it's a widely used PHP library for separating presentation and logic.
Let's make it clear what is not separation
you switch from php mode to html mode
you use print or echo statements to write out html code
you use small php snipplets inside html files
If you do this, there is no separation at all, no matter if you escape from php to html blocks or do it the other way and put php code into html.
Have a look at a good templating engine, there are a plenty of reasons in the "why use ...." parts of the manuals. I'd suggert www.smarty.net especially http://www.smarty.net/whyuse.php
It will answer all your questions now you have.
It is very important to separate application logic from presentation logic in projects. The benefits include:
Readability: Your code will be much easier to read if it does not mix PHP and HTML. Also, HTML can become difficult to read if its stored and escaped in PHP strings.
Reusability: If you hard-code HTML strings within PHP code, the code will be very specifc to your project and it won't be possible to reuse your code in later projects. On the other hand, if you write small functions that do one task at a time, and put HTML into separate template files, reusing your code in future projects will be possible and much easier.
Working in a team: If you are working in a team that contains developers and designers, separation of application logic and presentation templates will be advantageous to both. Developers will be able to work on the application without worrying about the presentation, and designers (who don't necessarily know PHP very will) will be able to create and update templates without messing with PHP code.
for pages that contain a lot of HTML, embedding PHP code into the page could be easier. this is one of the first intentions behind PHP. anyway when you are developing an application with lots and lots of logic, different types of connectivity, data manipulation, ... your PHP code gets too complicated if you want to just embed them in the same pages that are shown to users. and then the story of maintenance begins. how are you going to change something in the code, fix a bug, add a new feature?
the best way is to separate your logic (where most of the code is PHP) in different files (even directories) from your page files (where most of the code is HTML, XML, CSV, ...).
this has been a concern for developers for so many years and there are recommendations to handle these general problems, that are called design patterns.
since not everyone has the experience, and can apply these design patterns into his application, some experienced developers create Frameworks, that will help other developers to use all the knowledge and experience laying in the hear of that framework.
when you look at toady's most used PHP frameworks, you see that all of them put code into PHP Classes in special directories, make configurations, and .... in none of these files you see a line of HTML. but there are special files that are used to show the results to users, and they have a lot of HTML, so you can embed your PHP values inside those HTML pages to show to users. but remember that these values are not calculated on the same page, they are results of a lot of other PHP codes, written in other PHP files that have no HTML in them.
I find it preferable to separate application logic from the view file (done well with CodeIgniter framework with MVC) as it leaves code looking relatively tidy and understandable. I have also found that separating the two leaves less margin for PHP errors, if the HTML elements are separated from the PHP there is a smaller amount of PHP that can go wrong.
Ultimately I believe it is down to preference however I feel that separation has the following pros:
Tidier Code
Less of an Error Margin
Easy to Interpret
Easier to change HTML elements
Easier to changed Application Logic
Faster Loading (HTML is not going from Parser->Browser it goes straight to browser)
However some cons may be:
It only works in PHP5 (I Believe, could be wrong, correct if needed)
It may not be what one is used to
Untidy if done incorrectly (without indentation etc, however this is the same with anything)
But as you can see, the pros outweigh said cons. Try not to mix the two also, some separation and some intergration - this may get confusing for yourself and other developers that work with you.
I hope this helped.
Benefits of the first method (separating PHP and HTML):
You don't need to escape characters
It's also possible for code editors
to highlight/indent the markup.
It's arguably easier to read
There is no downside to this method,
compared to the second method.
Functionally: they both will work, so ultimately it is a preference.
Yet, you might consider that comments are a preference as well, your code would compile and run exactly the same without comments. However most people would agree comments are essential to writing and maintaining good code. I see this as being a similar subject matter. In the long run it will make it easier to read and maintain the code it if the two are separated.
So is it important? I would say Yes.
I kick off with: the first one you can open in a WYSIWYG editor, and still see some markup, which might makes it easier to maintain.
It says that what you put in echo '' it is first processed by the programming language and then sent to the browser, but if you directly put there html code without php, that code will load faster because there is no programming involved.
And the second reason as people above said is that you should have your 'large programming code' stored separately of the html code, and in the html code just put some calls to print results like 'echo $variable'. Or use a template engine like Smarty (like I do).
Best regards,
Alexandru.
Ouch!
All of the examples in your question are perfectly impossible to read. I'd say, you do yourself and those, who might read your code a great favour and use a template engine of sorts, say, Smarty. It is extremely easy to set up and use and it WILL separate your code from presentation. It doesn't require you to put everything in classes, it just makes sure, that your logic is in one file and presentation - in another one.
I don't know how in php but in asp.net separation has the following advantages.
1. separated code is easy to understand and develop
2. designer can work in html in the same time developer can write a code