Reputation: 24305
I'm trying to figure out what is the best way to clone/template HTML that is frequently repeated in my web app. For example, I have a voting <form>
(see below) that needs to be located on several pages.
Two ways I thought of doing this:
voteForm($action, $user_id, $formType, $success);
include
statement, e.g., include '/myApp/views/voteForm.php'
I prefer an include
statement b/c:
include
statement, I can just use the variables as they are wherever I put the include
d php file (avoiding redeclaring them which is a pain b/c there are often lots of variables).Should I reconsider using include
instead function()
for any reasons (e.g., performance)? Are there are other templating solutions I'm not thinking of?
<form action="<?=$action?>" method='post' data-form-data='{'formType': '<?=$formType?>', 'success': '<?=$success?>'} >`
<input type='hidden' value='<?=$user_id?>' name='user_id'>
<input type='radio' value='1' name='vote'>
<input type='radio' value='-1' name='vote'>
</form>
Upvotes: 1
Views: 109
Reputation: 101604
It's really up to you--you could have a hybrid of a function
that calls include
for you (setting up any necessary variables that the include file may need for display purposes). e.g.
function createForm($action,$foo,$bar){
$form_action = $action;
$form_foo = $foo;
include('templates/form.inc');
}
As far as performance, there's no huge benefit that I'm aware of. Although If you're looking for a better way for templating, you may want to look at smarty or some other system that handles most of the 'tough work' for you.
Just keep in mind that when you have code outputting HTML you no longer have a separation of concerns. That is to say that if you decide to change the look and feel of the site at a later date you're not looking through just .inc
(or whatever extension you've used) files, but now both .inc
and .php
files to apply changes.
Upvotes: 1
Reputation: 14774
For big blocks of generated HTML, I'd recommend using includes. I prefer to use function calls to get specific bits of data back.
The again, this is personal preference and cannot be answered with a truly 'correct' answer.
In terms of performance, I would guess not much difference at all unless you're making thousands of calls on each one in one go.
Hope that helps.
Upvotes: 0
Reputation: 30565
I would try to avoid putting HTML into function calls. I think what your trying to achieve here would be best suited to an include statement - based on personal preference.
As for performance - it's hard to tell but you could use a PHP Profiler like XDebug to see whether a function or include is the most efficient.
http://xdebug.org/docs/profiler
Upvotes: 0