开发者

How can i make my own template/programming engine in php

Ive been working some time on own template engines but i alwais get stuck in strucktured documents like

<block : block1>
    <table>
        <block : row>
            <tr>
                <td>
                    {value}
                </td>
                <td>
                    {value2}
                </td>
            </tr>
        </block>
    </table>
</block>

I can get "block 1" with a regex but it will break at the f开发者_运维问答irst (the one of "row")

But i want a smarter way (and not by using a function like DOM) i was thinking about something like

while($i < strlen($code)){
    if(substr($code,$i,1)){
        //tag is opened
    }
}


Basically, you're constructing a programming language here (albeit simple, it's still a programming language). To interpret a programming language you need a compiler, which usually contains a lexer (which splits input stream into meaningful tokens) and a parser (which reads tokens one by one and takes whatever actions are needed). In your simplified example, the lexer would be probably regexp-based, and the parser can be a simple stack-based one.

(terms in italic should actually be wikipedia links).


I am not entirely sure about what your question is, but there has been a lot of debating about templating languages in PHP but I think a general consensus reached by now was that it usually doesn't make much sense to roll your own templating language. You might get instant nice result by e.g. using string replacement and regular expressions, but eventually you will need more functionality like loops or other expressions and then it will become quite tricky (ultimately ending in creating your own compiler).

The best suggestion usually is to either use PHP as your templating language directly (that is what PHP was designed for in the first place and with strictly following the MVC pattern quite a good solution, too) or try one of the existing templating engines. Only if you can't make any of them fit your needs (most of them are extensible through a plugin mechanism) you should start making your own.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜