开发者

Preferred way to combine PHP and HTML?

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:

  1. 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 print​ed out in the middle of a load of business logic.

  2. 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.

  3. 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/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜