Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it a bad idea to return the html code from a function or method?

Tags:

php

I have this idea:

when someone calls mysite.com/layer1/layer2/something, then I want to start the action called something. That action is simply a file in an actions directory which contains a function. This function takes some context parameters and is supposed to return HTML output. This output, which goes into a variable, will then be brought into an main template, and finally the little framework will throw out the whole html output at once.

Now I don't know if it's good or bad design to return big amounts of html code from a function or method?

like image 277
openfrog Avatar asked Feb 25 '26 21:02

openfrog


2 Answers

This is likely nothing to be concerned with. Just make use of caching if necessary.

like image 71
Sampson Avatar answered Feb 28 '26 13:02

Sampson


There's nothing wrong with returning HTML from a function provided that function lives in the presentation layer and you maintain good seperation of business/controller/presentation logic.

However, in this particular case, I'd recommend having your "action" files just dump their output via echo, and capturing it with output buffering wherever you're doing your original function call. This way, your action files don't have to worry about concatting a bunch of data onto a buffer variable and making sure it gets returned. Also, because these files are (presumably) largely HTML oriented, you'll be able to use the much nicer and more legiable syntax:

<div id="Outer">
  <?= $content ?>
  <p class="Inner">
    <?= $more_content ?>
  </p>
</div>

As opposed to:

$buffer .= '<div id="Outer">' . $content .
           '<p class="Inner">' . $more_content .
           '</p></div>';

At the very least, the first way allows your IDE/editor to perform proper syntax highlighting.

like image 38
meagar Avatar answered Feb 28 '26 13:02

meagar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!