2

What is the best practice, to write my PHP code inside my HTML code or HTML inside PHP?

PHP inside HMTL:

 <p class="lead">Welcome to the <?= COMPANY_NAME ?> website.</p>

HTML inside PHP:

 <?php
      echo '<p class="lead">Welcome to the ' . COMPANY_NAME . ' website.</p>';
 ?>

Is there a difference in performance? Which is the best practice? As in, which would produce code that is best maintained.

Also COMPANY_NAME is defined as such:

define("COMPANY_NAME", 'MyCompany');
  • use output buffer (php.net/manual/en/book.outcontrol.php) when you can. if you can't, format the code in a way that is well formatted and suited to read a dom structure – Brandt Solovij Aug 4 '15 at 16:55
  • Sharing your research helps everyone. Tell us what you've tried and why it didn’t meet your needs. This demonstrates that you’ve taken the time to try to help yourself, it saves us from reiterating obvious answers, and most of all it helps you get a more specific and relevant answer. Also see How to Ask – gnat Aug 4 '15 at 17:12
  • There are lots of ways to approach this, and performance is almost certainly not the right criteria focus on. Your HTML inside PHP is probably not the best, because it makes writing structured HTML very hard. I recommend using an actual template engine, but others say "PHP is already a template engine" and (presumably) use variations of PHP inside HTML. – grossvogel Aug 4 '15 at 17:14
  • @gnat It is not necessarily about needs. They both work. Mostly I just write HTML inside the PHP, but there is no reason for it. I am looking for what can qualify as good practice. That is what this exchange site is mostly about, yes? – J_Strauton Aug 4 '15 at 17:28
  • 1
    This toes the line between "good subjective" and "bad subjective". I've seen situations where each have their merits. – zzzzBov Aug 4 '15 at 18:36
4

What about:

Neither

Mixing languages is not a good idea. You don't put JavaScript in HTML, or HTML in JavaScript, or JavaScript in PHP, or HTML in Python or Ruby in SQL.

Why don't we do that?

Because different languages usually correspond to different layers.

PHP deals with business logic. HTML deals with presentation of the business objects. Thus, you have two layers: the one generates the objects; the other one builds a pseudo-XML representation of those objects.

In the same way, JavaScript deals with interaction, and CSS with the presentation of the content. When you want to change interaction, you don't open an .html file, and you surely don't open a .php file: you open a .js or .coffee file.

By mixing logic within the same file, you'll quickly notice that maintaining the code becomes more and more difficult. You want to change the method which applies rebates to products, and you spend fifteen minutes browsing through a mix of HTML with PHP statements here and there, and PHP code with HTML all over it.

The fact that technically, PHP makes it possible to mix HTML and PHP is irrelevant. The feature is available for historical reasons, but shouldn't be used any longer.

So what should you do?

What are you probably looking for is called templates. Depending on the framework you use, it may already be available, usually under a form of MVC, where the template is in the view, or you may have to use a third-party template engine, such as Smarty.

In both cases, the idea remains the same. You have PHP code strictly separated from the template which contains the HTML and a bit of very simplistic logic: simple loops over entities, conditions for conditional displaying of information, etc. When the PHP code is ready, it calls the template engine, passing to it some information. The engine uses a specific template to build the final output (often HTML, but other formats are possible as well) which is then sent to the user.

By using templates, you make sure that you have a strict separation between the business logic and the form you give to this logic through the templates. One day, you can throw all those templates and write other ones, without modifying a single line of PHP code. Or you may create a bunch of templates for a mobile version of the website.

An additional benefit is that you are not even stuck with HTML. If you need to make an API which is based practically 1:1 on the actual web pages of the website, instead of applying the template, you serialize to JSON the object which was about to be sent to the template engine. With practically zero efforts, you add API capability to an app, thing which couldn't be possible without severe rewriting if you were mixing PHP and HTML.

  • 1
    ...I haven't read the full details of your reply, but one objection that I can identify is that -even with the goal of keeping presentation and business logic separate- you do mix javascript and html when you register click events and it is quite possible that you will use javascript to compose a template from fragments. Your overall point that "you should keep your concerns separated" is taken, but the layers have to eventually be tied together to create working software. – K. Alan Bates Aug 4 '15 at 20:03
  • @K.AlanBates why? If you have convention control, why would you do that? (honest question) – Brandt Solovij Aug 4 '15 at 20:40
  • @BrandtSolovij We're likely arguing semantics. (Sticking to html and javascript) You have to include some javascript in your html page or you cannot tie your presentation layer into your script. <span class="button" onclick='goRunJavascriptStuffs(document.getElementById("foo")'>Do Stuff</span> 'goRunJavascriptStuffs("foo")' is javascript. – K. Alan Bates Aug 4 '15 at 20:51
  • 1
    "you do mix javascript and html when you register click events": why would I do that? Registering events can (and often should) be done exclusively in JavaScript. Agreed, onclick attributes were used fifteen years ago because alternatives weren't that popular and because JavaScript was considered "a language to add annoying animations to a website", but why would anyone still use them today? – Arseni Mourzenko Aug 4 '15 at 20:58
  • @MainMa well...if you were to say "just put it into your Javascript" then you're tying your business logic to the DOM,so you have the opposite side of the same problem of saying "must keep them separate." My point was simply that you have to eventually tie them together.In a traditional MVC architecture,your view knows about "something" on the controller but the controller knows nothing about the View.It is your view's responsibility to attach to the ctrl, so you would either tie an action performed against the host to trigger functionality or you would create a binding script inside the view. – K. Alan Bates Aug 4 '15 at 21:20
1

You would have a better chance of resolving Sunni/Shite differences than you will of getting a clear answer to this sort of question.

For myself, I like React's notion of components and PHP s heredoc syntax.

class CompanyComponent
{
    public function __construct($company)
    {
        $this->company = $company;
    }
    protected function escape($string)
    {
        return htmlspecialchars($string, ENT_COMPAT | ENT_HTML5, 'UTF-8');
    }
    public public function render()
    {
        $companyName = $this->escape($this->company['name']);
        return <<<EOT
<p class="lead">Welcome to the {$companyName} website.</p>
EOT;
    }
}
$companyComponent = new CompanyComponent(['name'=>'Trump']);
echo $companyComponent->render();
  • Noting that you said that the opposite of a Sunni is a "Shite." Expect someone to declare a jihad on you for that. – K. Alan Bates Aug 4 '15 at 20:07
0

The most readable is php in html but only a little. You should split your file in two parts. Logic in the top. Here you prepare all variables but no html.

In the bottom you put html with variables and a loop or two but little to no logic.

Of course this doesn't scale all that well. For larger projects you should probably use a mvc framework.

-1

I think it depends. If you are just using a little bit of PHP to create a list via looping, it makes sense to put it in the HTML. If your PHP is extensive and is generating the bulk of the HTML, it could make sense to do HTML within PHP.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.