PHP/HTML - Spaghetti, fastest code for the server - php

I have a big page with much spaghetti code. I'm not sure which solution is faster for the server.
The first solution
<div> ... many html code ....
<?
if(isset($ubo['day']['xxl']['0']))
{
$firstHit = $ubo['day']['xxl']['0']['title'];
echo "<div style=\"cursor:pointer;\">$firstHit </div>";
}
?>
... many html code .... </div>
this solution ( I use ' instead of " )
<?
// many php code
if(isset($ubo['day']['xxl']['0']))
{
$firstHit = $ubo['day']['xxl']['0']['title'];
}
// one echo with all html code
echo "<div> ... many html code ....
<div style='cursor:pointer;'>$firstHit </div>
... many html code .... </div>";
?>
or this solution
<?
// many php code
if(isset($ubo['day']['xxl']['0']))
{
$firstHit = $ubo['day']['xxl']['0']['title'];
}
// one echo with all html code
echo "<div> ... many html code ....
<div style=\"cursor:pointer;\">$firstHit </div>
... many html code .... </div>";
?>

Practically, it doesn't really matter. What matters is that your code is maintainable and clean. You should look into using a PHP framework like CodeIgniter or CakePHP to make your code more well-structured.

You should have as little HTML inside PHP echo/print statements as possible; it is good to close PHP tags and just have the natural HTML. This is because the parser won't travel through the echo/print statement and and parse it. Thus, your first solution is certainly the best in terms of speed.

Of the solutions presented, I would say that the first is probably best. General rule is that you should put as much into strait HTML as possible. This is both for the developer's sake as well as the server's. Stuff outside of <?php ?> is basically raw data which, while it still needs to be parsed on some level, can basically be served to the user straight up.
If anything, you may want to refine it further:
<!-- as a note: in all of your examples except the first, this div exists.
In the first it only exists if the isset returns true. -->
<div style="cursor:pointer;">
<php?
if(isset($ubo['day']['xxl']['0']))
{
echo $ubo['day']['xxl']['0']['title'];
} ?>
</div>
You also could probably optimize through storing $ubo['day']['xxl'] in some local variable elsewhere on the page.

Do you have performance problem ? If no don't bother about "better for the server" and do "better for your code" instead.
And i'd say that all this is the same, most of the performance are due to I/O (sql query/web service, hard disk) not syntax details.
So do the best code for yourself you'll see later about performance.

The second solution might be faster than the first, because you are sending the content only once and it also looks a little better (PHP is more separated from HTML).
However performance difference between all 3 solutions will be very small and you really should't put attention to it.

Follow the hint "premature code optimization is evil" :-) I dont think that it makes a (big) difference what you use in your given code. It would be much better to have a clean code separation in mvc. Then you can use a template engine which supports caching for your massive html code and there's no need to output it every time with an echo! Besides this performance optimization has much more effect on DB-issues, your general code structure and the code at client side. For example, avoid inline css styles to reduce transferred html code.

do you use PHP opcode cache?
do you use memcached for generated subpages?
have you optimized your database queries?
do you use icongroup images? do you compress JS and CSS?
have you really run out of all the low hanging fruits?

Related

PHP - start / end PHP multiple times in HTML file

I have a HTML file where I am using PHP like this:
...
<?=$someVariable;?>
<html code>
<?php do something ?>
<?php do something ?>
<div>
<?php do something ?>
</div>
<?php do something ?>
...
Is this a good way to go, or should I put entire HTML to PHP echo? I mean, I am starting / stopping script inside web page multiple times just because of one output one variable or if some block of the HTML code.
I am doing it this way fo better readibility of HTML/PHP code during development.
Your question of "which way is better" can be broken down into two questions:
Which way is more efficient?
Which way is more readable?
The answer to question 1 is that the difference is negligible. PHP code is made to execute very fast on the server. Usually processes that take long on PHP would be complex functions that require iterations over large amounts of data for instance, however the actual reading of a single tag takes a very small amount of time to be processed.
The answer to question 2 depends entirely on the situation. In your situation, you are constantly adding <?php and ?> tags when you could have done it all at once, so my personal opinion would be to place it all in one echo, however there are many cases where it is more readable to place separate php elements, for example in the following form:
<form action="<?php htmlspecialchars($_SERVER['PHP SELF']);?>" method="POST">
<?php echo $dynamic_input1'?><br>
<input type="text" name="text1">
<?php echo $dynamic_input2'?><br>
<input type="text" name="text2">
</form>
Let me know if that helped.
You should start to use templates (read: viewmodels).
To keep readable the HTML you can move to logic to the top of PHP file and leave only the variable printing into the HTML code.
I'm not really a fan of multiple html/php blocks. What I normally use is heredoc, here's an example:
<?php
$myTitle = "Heredoc is Cool";
$myArray = array(array('someIndex' => '1st Paragraph'), array('anotherIndex' => '2nd Paragraph'));
echo <<< LOL
<!DOCTYPE html>
<html>
<head>
<title>{$myTitle}</title>
</head>
<body>
<h1>{$myArray['0']['someIndex']}</h1>
<p>{$myArray['1']['anotherIndex']}</p>
</body>
</html>
LOL;
?>
Using heredoc helps me write code without the need of concatenation, quotes and several blocks of php between html, which can be confusing sometimes. Heredoc also helps my code to be more readable.
This reduces the performance a little bit. too little. If you are more concerned about the readability of code, you can manage you code in different files and categorize the code (This is my personal technique). For Example a code for HTML 'Like' button will be like.txt file. Whenever I want to use the Like Button i just add
file_get_contents("like.txt");
This technique will increase flexibility of the code but again will reduce the performance a little (as you are opening files). For this technique to follow you have to maintain a class Architecture Diagram, Class Diagram, Use Case Diagram and other this.
This is the basic hurdle of programming (Quality Assurance). Increasing one thing may reduce another i.e. Increasing Interoperability and Flexibility will reduce Performance (depends how much). So you have to measure what you need the most in a particular Software project.

Adding large quantities of HTML with Jquery/javascript

I'm working on a form that auto-generates a large addition when the user specifies, including a editable canvas, selectable inputs, textareas and so on. I'm wondering if there's a tool for appending large blocks of HTML more easily and with better style: for instance, in my codeigniter PHP views it's easily done just by closing the PHP tag and referencing variables using <?=var?>.
<?php if (condition) {?>
<h1>List a variable <?=$var?></h1>
<?php }?>
Is the above terrible style? Is there a comparable tool to use for javascript so I can include html with proper indentation?
EDIT:
To be clearer, I'm not looking for a lot of input on the php - my objective is to make editing the HTML I'm inserting with javascript cleaner.
The problem is analogous to this:
<?php
if (condition) {
echo "<div>";
echo "<p> a line of html code<p>";
echo "<h1> more stuff and a ".$variable;
echo "<div>";
}
?>
//vs
<?php
if (condition) { ?>
<div>
<p> A line of html code, but easier to edit</p>
<h1> a <?=$var?>
</div>
<? } ?>
The second one is cleaner and easier to edit for the developer. So I'd like to do the same with javascript and take this:
$(this).append('<p>a whole bunch of stuff'+var+'more stuff<p>');
$(this).append('<p>more stuff<p>');
$(this).append('<h1>more stuff<h1>');
And make it easier to manage.
Indentation is for the DEVELOPER, to make source code maintainable and readable. It has nothing to do with making "view source" look nice.
It does look a little unpleasant, certainly.
I'd probably write it like this, if I was using that particular approach to page generation.
<?php
if (condition)
echo "<h1>List a variable $var</h1>";
?>
You may also like to look into the DOM methods of php. They can make creating reusable, modular code much easier.
They're not as fast as simple string operations, but far neater and more powerful. When the daily traffic means this difference in speed is a problem you've probably got the money to throw at some ode monkey to make the required changes.
Try CoffeeScript. It adds some features to normal javascript like string interpolation, block strings and stuff that makes writing huge blocks of HTML string literals a piece of cake.

HTML within PHP

I usually create modular websites, each part of the website being a .php file which will be included in the main pages.
Is it "better" to output HTML within PHP files using echo or to close each time the php tag ?> and open it each time I need to access a PHP function/variable.
V1:
<?php
$v1=$_POST['name'];
echo "Your name is".$v1;
echo $v1." if you want, you can log out";
?>
V2:
<?php $v1=$_POST['name']; ?>
Your name is <?php echo $v1; ?>
<?php echo $v1;?> if you want, you can log out
The thing is that between the php tags there's much more HTML code (echoed) than actual PHP.
Does it affect the script performance if I close the tags each time? And is it safe to acces variables declared in a previous block of php code?
EDIT1:
When closing the php tags isn't the server clearing some cache for that script, or something like that?
I think you can select whatever you want, but you should use it everywhere. For myself, second one is better
Definitely v2. Plus , you additionally should read this one : http://codeangel.org/articles/simple-php-template-engine.html (archive link: http://archive.is/CiHhD).
Using V2 would be better as it wouldn't break the syntax highlighting or code completion in many IDEs, but both of them are as good as the other.
As far as I know, there is no (considerable) difference in performance.
You could also consider using a template engine, however, that does impact performance. The most popular template engine is Smarty, but there are others (some better, some worse) out there.

Embedidng PHP code in HTML?

I am just wondering if its normal to embed PHP in the HTML, or is it considered dirty/unprofessional. For example consider following lines:
<? if($photo == 0) { ?>
<div class ="reminder">Hey <?=$name;?>, You don't have any photo. </div>
<? } else { ?>
<div class ="ok">Do you want to change your photo? </div>
<? } ?>
Is this kind of code ok? How the similar work can be done in a clean/professional way (without PHP frameworks? )
Thanks.
As long as you keep the logic of your program outside the html, it is ok. You need to mix it in your templates, for example. Template-engines like smarty replace the {$myVar} with < ? php echo $myVar; ? > (simply spoken), so it is not possible to avoid it completely. But things like
<?php
include "db.php";
connect_db();
// check login
echo "< html >< head><body>...";
?>
is NOT good practice, because you mix everything together: program logic (login-check, db-stuff) and output (echo html). Just have a look at the MVC and keep the "separation of concerns" in mind.
Your example looks ok because you have only that logic in your html which is needed to control the output directly. But calculating the value of $photo, depending on a db entry for example, would NOT be good in your html, because this is program logic. Output (HTML) and logic should be devided all the time.
It's very normal, whether it's good or not is a completely separate topic. It's really all about the size of your project and your requirements for maintainability/flexibility.
If it's a small project, just do what you have to in order to get it done. However a point exists at which it becomes unwieldy to develop without a framework. This is all very subjective and varies from project to project, but this is the general principle.
It's OK to use PHP in templates but many people prefer to work with a templating language because it forces separation and ensures you don't litter your templatse with loads of PHP. If you do go down the template route Twig and Smarty are quite good since they compile the template into PHP which speeds things up.
If you're writing PHP in your templates try to follow some best practise coding standards to keep things neat. For example:
Use full <?php tags for compatibility.
When writing any loops instead of curly braces use colons. To end the statement you need to explicitly write it as endforeach/endif/endwhile/etc. This makes PHP templates more readable.
If you have a lot of logic move this into an external PHP file to keep the PHP in your template short and readable
If there is only one PHP statement in your PHP tag you don't need to end it with a semi-colon. Again, helps readability
An example:
<?php if ($photo == 0): ?>
<div class ="reminder">Hey <?php echo $name ?>, You don't have any photo.</div>
<?php else: ?>
<div class ="ok">Do you want to change your photo?</div>
<?php endif ?>
See more at:
http://www.php.net/manual/en/control-structures.alternative-syntax.php
http://framework.zend.com/manual/en/coding-standard.overview.html
for that you can use smarty templete .... it improves your coding style and works fast ... visit smarty and try it, it's really awesome
From what I have read either will work, but most people just use the echo statements for small, conditional html.
I try to keep this at a minimum, because i find it harder to debug it with all the
< ? } ?>
flowing around in the code (wordpress theme gurus does this alot)
There will be many opinions about this. Mixing HTML and PHP can become very messy, but this looks fine. Many professionals work just this way. If it works for you, it's good.
To make it more readable, I tend to keep the brackets on separate lines, just so you can be sure to be able to find them all easily, but thats just me.
there was an answer from guy named alexn
Dunno why did he delete it, it's looks best answer to me, so, I am only reproducing it:
I would say that's the way to go. You
have a nice, clean separation of PHP
and HTML.
Here's another option:
<? if($photo == 0): ?>
<div class ="reminder">Hey <?=$name?>, You don't have any photo. </div>
<? else: ?>
<div class ="ok">Do you want to change your photo? </div>
<? endif ?>

PHP echoing HTML code with more PHP included

I have blocks of HTML code in a MySQL database and my framework needs to print these within a PHP template which will be outputted to the browser. To do so I make this call:
</tr>
<!-- Section 3 -->
<?php echo SIN_SiteView::get('section3') ?>
<tr>
Which gets the code either from the APC or MySQL, now the code it obtains looks like this:
<td height="280" colspan="2" bgcolor="#00abd2">
<a href="#">
<img src="<?php echo SIN_Utilities::l("image", "home_flash.png")?>" width="710" height="280" border="0" />
</a>
As you can see I need to run all images through a method known as "l" which I use to easily change images paths. Now the issue is if I echo that block of code it will simply be echoed as a string and not work.
I tried surrounding the php with '. [code] .' and removing the php but that also did not work. Does anyone have any ideas on how I could properly echo this to the page.
Thanks.
UPDATE: I think I need to be using the eval() command thanks to some of the comments, I simply do not understand how to implement it in my situation. Any simple examples would be greatly appreciated, for example how do I change this line:
<?php echo SIN_SiteView::get('section3') ?>
To echo the entire block featured above, thanks again.
I think you want eval rather than echo. See this slightly different question.
My solution would be to eval '?>'.$myhtml.'<?php'.
Is the marketing team adding the php code to the html you are storing?
If not, maybe you could change your <?php echo FUNCTION() ?> into #FUNCTION() and evolve your SIN_SiteView::get() into your own templating interpreter?
I agree with cHao though; it would probably be easier to adopt one of the templating packages out there and convert your data over.
You'll need to use eval to evaluate the inline PHP. However, this is potentially quite risky (eval is evil, etc.), especially if any of the content that's being fetched is user sourced.
e.g.: At the very least, what's the stop the user inlining...
<?php die(); ?>
...within the content they enter.
As such, you'll need to take a great deal of care, if there's really no alternative to this approach.
Some updates:
If you're new to PHP I'd recommend having a re-think. Chances are there's no need to use eval. (Unless there's a dynamically customised content on a per-user basis then you don't need it.) What are you trying to achieve?
What specific error/problem are you having? (I presume you're using var_dump or print_r for debug purposes, etc.) As the content you need to eval isn't pure PHP (it's HTML with PHP in) you'll need to embed the PHP close and (re-)open tags as #Borealid illustrated.

Categories