Templating HTML using PHP - php

I'm trying to figure out what is the best way to clone/template HTML that is frequently repeated in my web app. For example, I have a voting <form> (see below) that needs to be located on several pages.
Two ways I thought of doing this:
a function call, e.g., voteForm($action, $user_id, $formType, $success);
an include statement, e.g., include '/myApp/views/voteForm.php'
I prefer an include statement b/c:
Then I don't have to decide on the function's parameters which may change over time forcing me to rewrite the function calls everywhere they exists in my app. With the include statement, I can just use the variables as they are wherever I put the included php file (avoiding redeclaring them which is a pain b/c there are often lots of variables).
I can write the HTML in HTML and not as a PHP string where I have to deal with escaping characters/json_encode issues.
Should I reconsider using include instead function() for any reasons (e.g., performance)? Are there are other templating solutions I'm not thinking of?
<form action="<?=$action?>" method='post' data-form-data='{'formType': '<?=$formType?>', 'success': '<?=$success?>'} >`
<input type='hidden' value='<?=$user_id?>' name='user_id'>
<input type='radio' value='1' name='vote'>
<input type='radio' value='-1' name='vote'>
</form>

It's really up to you--you could have a hybrid of a function that calls include for you (setting up any necessary variables that the include file may need for display purposes). e.g.
function createForm($action,$foo,$bar){
$form_action = $action;
$form_foo = $foo;
include('templates/form.inc');
}
As far as performance, there's no huge benefit that I'm aware of. Although If you're looking for a better way for templating, you may want to look at smarty or some other system that handles most of the 'tough work' for you.
Just keep in mind that when you have code outputting HTML you no longer have a separation of concerns. That is to say that if you decide to change the look and feel of the site at a later date you're not looking through just .inc (or whatever extension you've used) files, but now both .inc and .php files to apply changes.

I would try to avoid putting HTML into function calls. I think what your trying to achieve here would be best suited to an include statement - based on personal preference.
As for performance - it's hard to tell but you could use a PHP Profiler like XDebug to see whether a function or include is the most efficient.
http://xdebug.org/docs/profiler

For big blocks of generated HTML, I'd recommend using includes. I prefer to use function calls to get specific bits of data back.
The again, this is personal preference and cannot be answered with a truly 'correct' answer.
In terms of performance, I would guess not much difference at all unless you're making thousands of calls on each one in one go.
Hope that helps.

Related

Including files and handling errors

By old habit I've always used require over include. Basicly the two functions are exactly the same - besides require throws an error if the file does not exist and thus stops the script - where include will just throw a warning and continue on with the script as if nothing happened.
Normally when I dynamically include files I use something along the lines of if file_exists then require it. Looking like this:
<?php if (file_exists($file)) { require $file; } else { /*error handling*/ } ?>
As far as I know, and please correct me if I'm wrong, this is widely accepted as best practice and the most efficient way to handle it.
But I thought of another approach, which seems to be slightly faster and smarter in my opinion:
<?php if (!include $file) { /* error handling */ } ?>
I have not tested it yet, but it seems logical to me that it should be faster than the file_exists/require combo, as that requires 2 harddrive interactions where the include approach only requires one.
From my tests it works as expected. It inherits the scope that you would expect and variables set in it is accessible.
Is there any reason not to do this?
edit: typo
edit 2: one argument against this could be the E_Warning thrown when it tried to include a file which does not exist. That could be avoided by passing # at include... Like this:
<?php if(!#include $file) { /* error */ } ?>
No, this is not a "best practice".
You'll be including a file in one of three cases:
if you need functionality from it - in other words, if your code would not function in the absence of that file
if your code could use some functionality from that file to provide extra features, but works without it
if your code could be enhanced by the inclusion of that file, but functions no differently without it (an example would be including a native SSL library versus using a pure-PHP one as a fallback; another example would be an "I need one of these libraries" situation, with all but the last falling into this grouping and the last one you try counting as "I need this" and going with the first bullet)
The only time you should use the if-include pattern you show here is in the second or third case, where having the file is nice but not necessary. In the first case, you should absolutely not do this - you should be using require. In the second case, you should strongly consider using include without the if statement. In the third case, you might use a conditional include, but see below.
The general "best practice" for managing includes in a PHP project where you can expect an include statement to ever fail without tanking the program is to define __autoload and have that handle your error correction, file-existence-checking, and so on.
To address your supposition that "it would be faster" to attempt the include and then detect failure: micro-optimization, especially that not backed by an empirical data, is the root of all evil. It doesn't matter whether it might be faster. First, determine whether you have a problem at all. If yes, then determine whether your include statements are significant enough in runtime that they're worth the programmer-hours you'd spend making them marginally better. If yes, then test whether your alternate implementation works properly. If yes, then benchmark both versions and see if the alternate is faster. Only then should you consider deploying it.

Are there any downsides from using Include() or nested include's()?

I am not an expert in PHP. I am trying to increase the use of include() to make my website code as clean as possible instead of just copying, for example, code of the header in all the pages. I have two questions
1 . Is it good practice to use include() a lot in terms of server requests, speed, ...etc ?
index.php
(bunch of code)
<? include("connect.php") ?>;
(bunch of code)
<? include("header.php") ?>;
(bunch of code)
<? include("footer.php") ?>;
2 . Is it fine also to use nested include's()? example:
header.php
(some code)
<? include("searchFormInput.php") ?>;
now index.php will include header.php, then header.php will include searchFormInput.php as well
is this fine?
Thanks a lot
Yes, including is a common practice.
Yes, including gives you slight performance penalty (very small).
But including gives you readibility gain and thanks to it will be easier to employ DRY rule. Just remember the following:
if the file contains some code that should be executed only once (some setup, class definitions, function definitions etc.), use include_once() (it will have no effect if invoked again on the same filename),
if the file contains some code executed multiple times (eg. some template for a form), use simple include(),
if something is required for your application to work (eg. some security code, some setup etc.), use require() instead of include() or require_once() instead of include_once() - if the file will not be found, PHP will throw fatal error and will stop executing your script,
The principle downside to nesting includes is that you are likely to run into situations when cross-dependencies cause a file to be include more than once. That is easily solved by the use of include_once(), though.
In your example however, with header.php including searchFormInput.php, you probably won't have problems assuming these files both mostly produce HTML output rather than parsing classes and dependencies.
On the other hand, if you had some structure like
connect.php includes config.php
session.php includes config.php
you would need to use include_once('config.php').
include,require will read file and excute codes inside it.
i made some tests on speed of include and file_get_contents
results was include and require is slow in compare
so my advice don't increase numbers of inclusion.
I think you should look at autoload with PHP once. You should not need to care the include of every and each file. Just adjust your autoload and that will take care of all these. You needs to do object oriented programming with this.
It's fine to that in terms of performance and it keeps your code clean and reusable to a certain extent. However, I recommend that you use templates for this kind of code inclusion, where you load all your information into variables and then call them in your template. Consider a template engine http://www.smarty.net/ or maybe a PHP framework or CMS http://drupal.org/ which should make your life easier in the short and long run!

PHP 5.3 Coding Standards: Anonymous functions in templates

I can not seem to find any documents stating if anonymous functions in templates are a good idea when templating HTML with PHP. I have the following code for example:
<html><body>
<?
$listMethod = function($items)
{
?>
<ul>
<?foreach ($items as $item):?>
<li><?=$item?></li>
<?endforeach;?>
</ul>
<?
};
?>
<?=$listMethod(array('1','2','3'))?>
<p> AND </p>
<?=$listMethod(array('a','b','c'))?>
</body></html>
Is this a good or bad way to create templates in PHP?
Bad bad way , it will be realy hard to debug them, edit, find, ... . You could include a template_functions.php file at the top of you're template and store all template related functions/helpers there .
Edit
Allso do not use short tags if you're into conding standards , most hosting companyes will allow them ( short tags ) but a few whont so you'll have problems .
Look at views as something that's just for output, nothing else.
Everything except echo, if and loops should concern you if in there. (Especially function definitions)
Is this a good or bad way to create templates in PHP?
That depends on whether or not you're intending to re-use that function in more than just one view. If you do, you might want to give the function a name, and put it somewhere so that multiple views can use it. If you don't want to use that function ever again, an anonymous function would do. Then again, I find anonymous functions to be less expressive than normal functions, so I don't think I'd use them for this precise purpose.
It's personal preference, though, and there's no consensus on this being good or bad.
Why scratch your left year with your right hand, as long as you have a left hand to do it? Best way is to define this as a classic function somewhere (myLeftyHelpers.php or whatever file). Although you made me wonder, I really do belive that the role of anonymus functions(if they work in PHP, never tried) are meant to act as function pointers, meaning that this way you can pass a function as a parameters to another function, that's the way I see them used. If someone thinks I am worng please correct me.

What are the advantages to putting your Javascript in a .php file?

I occasionally come across pages where some Javascript is included via a PHP file:
<html>
<head>
<script type="text/javascript" src="fake_js.php"></script>
</head>
<body onload="handleLoad();">
</body>
</html>
where the contents of fake_js.php might look something like this:
<?php header('Content-type: text/javascript') ?>
function handleLoad() {
alert('I loaded');
}
What are the advantages (or disadvantages) to including Javascript like this?
It makes it easy to set javascript variables from the server side.
var foo = <?=$foo?>
I usually have one php/javascript file in my projects that I use define any variables that need to be used in javascript. That way I can access constants used on the server-side (css colors, non-sensitive site properties, etc) easily in javascript.
Edit: For example here's a copy of my config.js.php file from the project I'm currently working on.
<?php
require_once "libs/config.php";
if (!function_exists("json_encode")) {
require_once "libs/JSON.php";
}
header("Content-type: text/javascript");
echo "var COLORS = ". json_encode($CSS_COLORS) .";\n";
echo "var DEBUG = ". ((DEBUG == true) ? "true" : "false").";";
?>
If you don't need it, don't use it:
The first thing you need to keep in
mind is YAGNI. You Ain't Gonna
Need It. Until a certain feature,
principle, or guideline becomes useful
and relevant, don't use it.
Disadvantages:
Added complexity
Slower than static files.
Caching problems (server side)
Scalability issues (load balancers offload static files from the heavy PHP/Apache etc processes)
Advantages:
User specific javascript - Can be achieved by initializing with the right variables / parameters in the <head> </head> section of the HTML
Page specific javascript - JS could also be generalized to use parameters
JSON created from database (usually requested via AJAX)
Unless the javascript is truely unique (i.e. JSON, parameters/variables) you don't gain much. But in every case you should minimize the amount of JS generated on the server side and maximize the amount of code in the static files. Don't forget that if it's dynamic, it has to be generated/downloaded again and again so it's not wanted for it to be a heavy process.
Also:
This could also be used to minimize the amount of server configuration (for example if the web server doesn't serve file.js with the correct content type)
There's no benefit for the example you gave above (beyond peculiar deployment scenarios where you have access to .php files and not .js files, which would be insane but not unheard of).
That said, this approach allows you to pass the JS through the php parser - which means you can generate your JS dynamically based on server variables.
Agree with tj111. Apart from what tj mentioned, I also found php-generated javascripts a great weapon to fight the browser's caching tricks. Not that long ago I was cursing the whole javascript for its being constantly cached by the browser. Refreshing the page helped me not, had to clear the whole cache in order to force the browser to reload the javascript files. As soon as I built a php wall in front of my javascripts:
fake_js.php:
<?php
header('Content-type: text/javascript')
include('the_real_javascript.js');
?>
A fresh new javascript would always show up at the client side. However this approach is obviously only good in the development phase, when it can save the developer quite some headache to have the correct javascript loaded in the browser. Of course when connecting to localhost, the penalty of repeatedly loading the same file is not as big.
In a live web application/site client-side caching is welcome to reduce network traffic and overall server load.
Advantage (not PHP specific - I used this technique in EmbPerl and JSP) would be the ability to dynamically generate or tweak/customize the JavaScript code on the server side.
An example usage would be population of an array based on the contents of a DB table.
Or application of localization techniques.
If you don't have full server access and can't turn on gzip encoding then it's pretty useful to put the following in your javascript file (note: will need to be renamed to file.js.php or parsed as PHP through .htaccess directive):
<?php
ob_start( 'ob_gzhandler' );
header("Content-type: text/javascript");
?>
// put all your regular javascript below...
You could also use it for better cache control, visitor tracking, etc in lieu of server-controlled solutions.
Absolutely none, IMHO. I use a js framework that I wrote to handle the setting of whatever server-side variables I need to have access to. It is essentially the same as embedding PHP in JavaScript, but much less ambiguous. Using this method allows you to also completely separate server-side logic and html away from javascript. This results in much cleaner, more organized and lowly-coupled modular code.
You could do something like this in your html:
<script type="text/javascript">
registry = {
myString : '<?php echo $somePhpString; ?>',
myInt : <?php echo $somePhpInteger; ?>
}
</script>
And then do something like this in your js:
if (registry.myInt === 1) {
alert(registry.myString);
}

How to setup site-wide variables in php?

I want to define something like this in php:
$EL = "\n<br />\n";
and then use that variable as an "endline" marker all over my site, like this:
echo "Blah blah blah{$EL}";
How do I define $EL once (in only 1 file), include it on every page on my site, and not have to reference it using the (strangely backwards) global $EL; statement in every page function?
Most PHP sites should have a file (I call it a header) that you include on every single page of the site. If you put that first line of code in the header file, then include it like this on every page:
include 'header.php';
you won't have to use the global keyword or anything, the second line of code you wrote should work.
Edit: Oh sorry, that won't work inside functions... now I see your problem.
Edit #2: Ok, take my original advice with the header, but use a define() rather than a variable. Those work inside functions after being included.
Sounds like the job of a constant. See the function define().
Do this
define ('el','\n\<\br/>\n');
save it as el.php
then you can include any files you want to use, i.e
echo 'something'.el; // note I just add el at end of line or in front
Hope this help
NOTE please remove the '\' after < br since I had to put it in or it wont show br tag on the answer...
Are you using PHP5? If you define the __autoload() function and use a class with some constants, you can call them where you need them. The only aggravating thing about this is that you have to type something a little longer, like
MyClass::MY_CONST
The benefit is that if you ever decide to change the way that you handle new lines, you only have to change it in one place.
Of course, a possible negative is that you're calling including an extra function (__autoload()), running that function (when you reference the class), which then loads another file (your class file). That might be more overhead than it's worth.
If I may offer a suggestion, it would be avoiding this sort of echoing that requires echoing tags (like <br />). If you could set up something a little more template-esque, you could handle the nl's without having to explicitly type them. So instead of
echo "Blah Blah Blah\n<br />\n";
try:
<?php
if($condition) {
?>
<p>Blah blah blah
<br />
</p>
<?php
}
?>
It just seems to me like calling up classes or including variables within functions as well as out is a lot of work that doesn't need to be done, and, if at all possible, those sorts of situations are best avoided.
#svec yes this will, you just have to include the file inside the function also. This is how most of my software works.
function myFunc()
{
require 'config.php';
//Variables from config are available now.
}
Another option is to use an object with public static properties. I used to use $GLOBALS but most editors don't auto complete $GLOBALS. Also, un-instantiated classes are available everywhere (because you can instatiate everywhere without telling PHP you are going to use the class). Example:
<?php
class SITE {
public static $el;
}
SITE::$el = "\n<br />\n";
function Test() {
echo SITE::$el;
}
Test();
?>
This will output <br />
This is also easier to deal with than costants as you can put any type of value within the property (array, string, int, etc) whereas constants cannot contain arrays.
This was suggested to my by a user on the PhpEd forums.
svec, use a PHP framework. Just any - there's plenty of them out there.
This is the right way to do it. With framework you have single entry
point for your application, so defining site-wide variables is easy and
natural. Also you don't need to care about including header files nor
checking if user is logged in on every page - decent framework will do
it for you.
See:
Zend framework
CakePHP
Symfony
Kohana
Invest some time in learning one of them and it will pay back very soon.
You can use the auto_prepend_file directive to pre parse a file. Add the directive to your configuration, and point it to a file in your include path. In that file add your constants, global variables, functions or whatever you like.
So if your prepend file contains:
<?php
define('FOO', 'badger');
In another Php file you could access the constant:
echo 'this is my '. FOO;
You might consider using a framework to achieve this. Better still you can use
Include 'functions.php';
require('functions');
Doing OOP is another alternative
IIRC a common solution is a plain file that contains your declarations, that you include in every source file, something like 'constants.inc.php'. There you can define a bunch of application-wide variables that are then imported in every file.
Still, you have to provide the include directive in every single source file you use. I even saw some projects using this technique to provide localizations for several languages. I'd prefer the gettext way, but maybe this variant is easier to work with for the average user.
edit For your problem I recomment the use of $GLOBALS[], see Example #2 for details.
If that's still not applicable, I'd try to digg down PHP5 objects and create a static Singleton that provides needed static constants (http://www.developer.com/lang/php/article.php/3345121)
Sessions are going to be your best bet, if the data is user specific, else just use a conifg file.
config.php:
<?php
$EL = "\n<br />\n";
?>
Then on each page add
require 'config.php'
the you will be able to access $EL on that page.

Categories