Is there an standard output library that “knows” that php outputs to html?
For instance:
var_dump– this should be wrapped in<pre>or maybe in a table if the variable is an array- a version of echo that adds a
"<br/>\n"in the end - Somewhere in the middle of PHPcode I want to add an H3 title:
.
?><h3><?= $title ?></h3><?
Out of php and then back in. I’d rather write:
tag_wrap($title, 'h3');
or
h3($title);
Obviously I can write a library myself, but I would prefer to use a conventional way if there is one.
Edit
3 Might not be a good example – I don’t get much for using alternative syntax and I could have made it shorter.
1 and 2 are useful for debugging and quick testing.
I doubt that anyone would murder me for using some high-level html emitting functions of my own making when it saves a lot of writing.
In regards to #1, try xdebug‘s
var_dumpoverride, if you control your server and can install PHP extensions. The remote debugger and performance tools provided by xdebug are great additions to your arsenal. If you’re looking only for pure PHP code, consider Kint or dBug to supplementvar_dump.In regards to #2 and #3, you don’t need to do this. Rather, you probably shouldn’t do this.
PHP makes a fine HTML templating language. Trying to create functions to emit HTML is going to lead you down a horrible road of basically implementing the DOM in a horribly awkward and backwards way. Considering how horribly awkward the DOM already is, that’ll be quite an accomplishment. The future maintainers of your code are going to want to murder you for it.
There is no shame in escaping out of PHP to emit large blocks of HTML. Escaping out to emit a single tag, though, is completely silly. Don’t do that, and don’t create functions that do that. There are better ways.
First, don’t forget that
printandechoaren’t functions, they’re built in to the language parser. Because they’re special snowflakes, they can take a list without parens. This can make some awkward HTML construction far less awkward. For example:Next, PHP supports heredocs, a method of creating a double-quoted string without the double-quotes:
With these two tools in your arsenal, you may find yourself breaking out of PHP far less frequently.
While there is a case for helper functions (there are only so many ways you can build a
<select>, for example), you want to use these carefully and create them to reduce copy and paste, not simply to create them. The people that will be taking care of the code you’re writing five years from now will appreciate you for it.