views:

48

answers:

3

Hey all,

I'm trying to do some templating optimizations and I'm wondering if it is possible to do something like this:

function table_with_lowercase($data) {
    $out = '<table>';
    for ($i=0; $i < 3; $i++) { 
        $out .= '<tr><td>';
        $out .= strtolower($data);
        $out .= '</td></tr>';
    }
    $out .= "</table>";

    return $out;
}   

NOTE: You do not know what $data is when you run this function.

Results in:

<table>
    <tr><td><?php echo strtolower($data) ?></td></tr>
    <tr><td><?php echo strtolower($data) ?></td></tr>
    <tr><td><?php echo strtolower($data) ?></td></tr>
</table>

General Case: Anything that can be evaluated (compiled) will be. Any time there is an unknown variable, the variable and the functions enclosing it, will be output in a string format.

Here's one more example:

function capitalize($str) {
    return ucwords(strtolower($str));
}

If $str is "HI ALL" then the output is:

  • Hi All

If $str is unknown then the output is:

  • <?php echo ucwords(strtolower($str)); ?>

In this case it would be easier to just call the function (ie. <?php echo capitalize($str) ?> ), but the example before would allow you to precompile your PHP to make it more efficient

+1  A: 

Define a CSS style and make the client side do the work, instead of the server side.

change_case {
    text-transform: lowercase; /* force text to lowercase */
    text-transform: uppercase; /* force text to uppercase */
    text-transform: capitalize; /* force text to proper case */
}

<span="change_case">...</span>

Thanks for the response. This is meant to just be an easy example, I'd like to be able to make general (more complex) functions that follow the same rules, that aren't necessarily easy to have the client-side manage.
Matt
+1  A: 

It's definitely possible. But, writing an effective optimizing compiler for php is no easy task. A simplistic one would probably not offer significant benefit. The benefit is even questionable for a good one.

chris
So you think I would be better off just running the function at runtime?
Matt
Not to say something like this wouldn't be nice to have, but the type of stuff you do in a template is unlikely to be a anywhere near being a bottleneck to your application. So, if you need/want to optimize, there's likely much more rewarding things to spend your time on. Profiling the code and application will help reveal what should be getting your attention.
chris
+1  A: 

Your best bet is probably to use a separate templating language that generates optimised PHP code. Smarty is a popular choice.

Sam Minnée
Thanks, I've used Smarty before - the overhead it has is unbearable. This question is the result of trying and hating smarty.
Matt