Menu Search
Jump to the content X X
Smashing Conf Barcelona

You know, we use ad-blockers as well. We gotta keep those servers running though. Did you know that we publish useful books and run friendly conferences — crafted for pros like yourself? E.g. our upcoming SmashingConf Barcelona, dedicated to smart front-end techniques and design patterns.

Getting Started With PHP Templating

In this article, we’ll cover how to separate the view of your PHP application from its other components. We’ll look at why using such an architecture is useful and what tools we can use to accomplish this. Here’s what we’ll cover:

  1. Learn some basic MVC concepts,
  2. Review some popular templating libraries,
  3. Play around with a small custom-made view class.
  4. Explore the basics of using the Twig library.

To fully benefit from this article, you should already know how to write and run your own PHP scripts on a Web server (i.e. using Apache).

Further Reading on SmashingMag: Link

A Quick Introduction To The MVC Pattern Link

In the early days of PHP applications, “spaghetti code4” was a familiar sight. Fragments of PHP code were mixed in with HTML mark-up. There were no frameworks, so Web applications were just a bunch of source files. As the PHP language matured, developers started to think about the cleanliness and maintainability of their code. The model-view-controller (MVC) pattern was introduced.

MVC is a software architecture that allows for the separation of business logic from the user interface. In this architecture, the user sees and interacts with the view that, in the case of Web applications, is generated HTML code (along with JavaScript, CSS, images, etc.)


User actions are passed (as HTTP requests, GET or POST methods) to the controller. The controller is a piece of code that handles and processes user input and then reads and makes necessary changes to the model, which is responsible for the storage and modification of data. (In simple terms, the model consists of the database structure and contents, and the code used to access it.) Then, the controller generates the proper view that will be sent and displayed to user.

Such separation of layers has many advantages…

Code Is Easier to Maintain Link

Because the model is separated, changing internal data relations without changing the rest of the application is easier. For example, the model for the user could provide the is_active() method, returning a boolean variable. In the business logic, it would be enough to check what value is returned by this method, without any knowledge of its internals.

You can also check for various conditions (for example, whether the user has confirmed their registration, paid their monthly fee, etc.), and you can change these rules in one place, without having to change anything in the other parts of the code. It also becomes easy to make a platform-independent application that allows for switching between database engines; this is often performed by ORM (object-relational mapper) libraries, which are a sub-layer of the model layer. ORMs add a level of abstraction to the library that accesses the specific database directly.

The Same Content in Multiple Views Link

Separating the view allows a single result to be presented in different forms. For example, based on some logic, a news page could be displayed in normal, mobile and RSS versions, all using the same content returned from the controller.

More Secure Link

Variables are escaped by default before being sent to the view, which is useful in applications that display user-generated content. Consider a variable with some unknown HTML or JavaScript code being passed to the view (which should never happen in your application). Escaping the variables prevents malicious code from being injected in such cases.

Better Code Link

Separating the layers forces the programmer to design better applications that are easier and cheaper to maintain. Also, designers and front-end developers don’t have to work with the business-logic code, because their task is only to display the contents of the variables that are provided to the view. This reduces the risk of the breaking some PHP code.

Today, every modern framework implements the MVC architecture. There are also some libraries that enable you to use selected features of the architecture. In this article, we’ll go over the recipes for the view, and in future articles we’ll cover the model and some ORM libraries.

Overview Of PHP Template Engines Link

As you might expect, many templating libraries allow you to separate the view layer from the rest of the application. In the most basic scenario, you can implement such a library by yourself (which we’ll do in the next section). You don’t even need a special library; sometimes it is enough just to separate your view (i.e. the template’s HTML files) into a different directory, prepare some variables in the simple controller (usually the main PHP file) and include the templates.

Every modern PHP Web application framework employs some kind of templating engine. Most of them use plain PHP by default (including Symfony 1.x, Zend Framework and CakePHP), but many standalone libraries can be plugged into your favorite framework or custom application.

Smarty Link


Smarty6 was one of the first and most advanced templating engines. It was developed as a sub-project of the main PHP project, but it has lost its popularity in recent years due to poor performance and forced backward compatibility with PHP 4. It has also lacked many modern features, such as template inheritance. Now, it is rising back to power with version 3. Many other frameworks (such as Twig7 and Django8) have inherited some of the basic concepts laid down by Smarty.

            User Information:
            Name: {$name|capitalize}
            Addr: {$address|escape}
            Date: {$|date_format:"%b %e, %Y"}



PHPTAL10 is a template language based on a very different syntax and concept; it implements the Zope Page Templates syntax (Zope is an application server written in Python). It is based on well-formed XML/XHTML, as in this example that comes from the project page:

<div tal:repeat="value values">
        <span tal:condition="value/hasDate"
        <a href="sample.html"
        tal:attributes="href value/getUrl"
            My item title
    <div tal:content="value/getContent">
        This is sample content that will be replaced by
        real content when the template is run with real

If you have prior experience with ZOPE or are a fan of XML, then this template engine is for you.

Twig Link


The last PHP template engine we’ll look at, and the one we’ll focus on in this article, is Twig12, from the authors of Symfony, which is the default view library of this framework’s 2.0 version. Its advantages are rich features, extensibility, good documentation, security and speed (it compiles your templates to the native PHP language).

    <head><title>My first Twig template!</title></head>
        My name is {{ name }}.
        My friends are:
        {% for person in friends %}
            <li>{{ person.firstname}} {{ person.lastname }}</li>
        {% endfor %}

The Basic Concept Link

Knowing how to use a particular library or framework is not enough. A good programmer should also know what is under the hood: how the stuff works, the relationship between the components, and possible caveats. For this reason, we’ll go over the concept with a simple templating library, custom-made for this tutorial. This should give you an idea of how more advanced libraries work. To run this code on your own, you will need to properly configure your HTTP server (with Apache), using PHP 5. No other libraries are needed.

Note: you can download this example code from the Mercurial repository on Bitbucket either by downloading the ZIP file13 or, if you have a command-line version of Mercurial installed, by entering the following command:
hg clone

First, let’s look at the code.

MyView.php: Templating Library Link

class MyView {
    protected $template_dir = 'templates/';
    protected $vars = array();
    public function __construct($template_dir = null) {
        if ($template_dir !== null) {
            // Check here whether this directory really exists
            $this->template_dir = $template_dir;
    public function render($template_file) {
        if (file_exists($this->template_dir.$template_file)) {
            include $this->template_dir.$template_file;
        } else {
            throw new Exception('no template file ' . $template_file . ' present in directory ' . $this->template_dir);
    public function __set($name, $value) {
        $this->vars[$name] = $value;
    public function __get($name) {
        return $this->vars[$name];

The main (and only) class of our templating engine is very simple. We use the “magic methods” (yes, that’s the official name) __set() and __get() to pass variables to the internal repository and then, in the template script, read from it. (A little explanation on magic methods: they are called when you try to read or write to nonexistent properties of the class. You can read more on this topic in the chapter on overloading in the official PHP manual14.) As a bonus, I’ve added a configurable template directory.

Invoking our library is straightforward. In this example, I’ve invoked two views, although different templates should be used in the actual application, depending on the application’s logic.

index.php: Controller Link

$t = new MyView();
$t->friends = array(
    'Rachel', 'Monica', 'Phoebe', 'Chandler', 'Joey', 'Ross'

The templates look like this…

index.phtml: HTML Template Link

        Names of my friends:
        <?php foreach ($this->friends as $friend): ?>
        <?php endforeach; ?>

index.xml: XML Template Link

<?='<?xml version="1.0" encoding="utf-8"?>'?>
    <?php foreach ($this->friends as $friend): ?>
    <?php endforeach; ?>

If you have basic knowledge of PHP, you can imagine how this works. Some logic is being used to set the variables, to read them from the database and so on, and then these variables are passed to the object of our view class. Next, we can access these variables in the template file, which is in HTML format, and the second one is XML (but could be in any other: JSON, plain text, CSS, JavaScript, etc.).

That’s the main idea behing the MVC model (without the “M,” in this example): the business logic happens in one place, while the content generation is sent to the user (or view) in another place. From one set of variables, you can generate many different views. In the template, you’re using plain PHP to display the variables.

Twig Library (With Tutorial) Link

The Twig library basically does the same job as the simple example above, but in a more sophisticated way. It has many useful features that enable you to develop and maintain your projects more easily and quickly.

Installation Link

Let’s start this short tutorial with the installation. Twig requires PHP 5.2.4 or above, but I assume that a PHP-enabled HTTP server (such as Apache) is already at your disposal. The easiest way to get it is to clone the repository on GitHub:

git clone git://

Or you could get it from the SVN repository:

svn co twig

Alternatively, you could install it using PEAR:

pear channel-discover
pear install twig/Twig

Lastly, you could get the file from the project’s download page15.

Configuring the Environment Link

Once the library is installed, you can start playing with it. I assume you will prepare your own application logic, which is beyond the scope of this article, so we’ll skip to the part where we already have something to display.

First, we’ll need to include the Twig library and register its autoloader:

require_once './twig/lib/Twig/Autoloader.php';

Notice that we have to provide the proper path to the Autoloader.php file, which is in the lib/Twig directory of the downloaded source package. This piece of code enables us to use all of the Twig libraries without having to explicitly include them. You should be familiar with this technique if you use other popular libraries or frameworks (such as Zend Framework and PEAR).

The next essential part of the Twig library is the loader. This is a class that tells the Twig engine how it should load the templates. With the object of this class, we can initialize the main part of the engine, the Twig environment. Here’s an example:

$loader = new Twig_Loader_Filesystem('./templates');
$twig = new Twig_Environment($loader, array(
    'cache' => './tmp/cache',

In this example, Twig_Loader_Filesystem is initialized with the directory where templates are stored as a parameter. An instance of the loader class is used to initialize the Twig environment as its first parameter. The second parameter is an array of options. The most important of them are these:

  • cacheThe directory where cached templates will be stored (more on the cache later). If you don’t provide a valid path here, the templates will not be cached (which is the default setting). Remember that you have to set the proper permissions for the cache directory so that your script can write there.
  • auto_reloadThis tells Twig to reload the templates every time they change. If it’s set to false, the templates will be reloaded only if you delete the contents of the cache directory. This is useful if you need to improve the performance of your website (and you rarely modify your templates).
  • autoescapeThis determines whether variables are escaped in the view automatically (the default is true).

Twig_Loader_Filesystem is the most common way to load the templates. For a parameter, you can provide a single string variable or (if you have two or more directories with template files) an array of strings. In such situations, Twig looks for the requested template files in the same order as the paths appear in the array.

Another loader that you might want to use in certain situations is Twig_Loader_String, which enables you to provide the template directly in the form of a string. This can be useful if you store your templates in some form other than files in a file system (for example, if you generate them dynamically, store them in the database, store them in some cache, etc.).

Twig is able to speed things up by caching your templates. That is, Twig processes the templates not every time you need them, but only once, when it detects that the template’s contents have changed (if you have enabled the auto_reload option). Pure PHP code is generated and stored in the cache directory. (Look into the cache files to learn about Twig’s internals.)

Templates Link

So, how do we display our first template? Let’s make it a simple “My name is [your name here]” page, with a list of some other items. First, prepare your template file. It will be very simple, because it contains only the basic output:

    <head><title>My first Twig template!</title></head>
        My name is {{ name }}.
        My friends are:
        {% for person in friends %}
            <li>{{ person.firstname}} {{ person.lastname }}</li>
        {% endfor %}

Save this file in the templates directory. The convention is to save a template with the .phtml extension, so let’s save ours as hello.phtml. Now we’ll prepare the script that will display the template. Its content will be as follows:

require_once './twig/lib/Twig/Autoloader.php';
$loader = new Twig_Loader_Filesystem('./templates');
$twig = new Twig_Environment($loader, array(
    'cache' => './tmp/cache',
$template = $twig->loadTemplate('hello.phtml');
$params = array(
    'name' => 'Krzysztof',
    'friends' => array(
            'firstname' => 'John',
            'lastname' => 'Smith'
            'firstname' => 'Britney',
            'lastname' => 'Spears'
            'firstname' => 'Brad',
            'lastname' => 'Pitt'

In this code, the Twig autoloader is included and registered. Then, we created the loader from the file system, which looks for the template files in the templates directory in our project’s root. In the next step, the environment is initialized with the previously created loader. We’ve enabled caching as a parameter by providing a path to the cache directory. As a result, the following code is sent to the browser:

    <head><title>My first Twig template!</title></head>
        My name is Krzysztof.
        My friends are:
            <li>John Smith</li>
            <li>Britney Spears</li>
            <li>Brad Pitt</li>

If you look again at the template, you will notice some basic rules:

  • The {{ … }} tag is used to print the variable or expression;
  • The {% … %} tag is used for flow-control statements, such as if and foreach;
  • You can access the array elements by using the myarray.item syntax. (It’s actually more sophisticated at the implementation level: it checks for the elements of the array, the object properties and their methods, and it even looks for the methods getItem and isItem — read more about it in the documentation).

But what if you want to send the browser an XML response rather than an HTML file? Nothing could be simpler. Just prepare the XML template, like so:

<?xml version="1.0" encoding="utf-8"?>
    <helloworld myname="{{ name }}">
        {% for person in friends %}
            <friend firstname="{{ person.firstname}}" lastname="{{ person.lastname }}"/>
        {% endfor %}

Save it as, say, hello.xml in the templates directory. To generate the result, just load this file instead of index.phtml in the PHP script, and you’re done. (Of course, in a real environment you might want to use more sophisticated logic to differentiate between the XML and HTML output).

This example shows how easy it is to use Twig. In the following examples, I will leave out the whole initialization and rendering phase, just to show the relevant pieces of the template’s code.

Filters Link

Filters are a useful concept and are common to many templating engines. Filters are applied to the variable to change its contents and print it to the template. Take the following code:

{{ myvar|upper }}

This will affect the variable being printed, and all lowercase letters will be switched to uppercase. Filters can be chained, too. So, you could strip out any HTML tags and convert the variable to uppercase with following code:

{{ myvar|striptags|upper }}

Filters can also take parameters. An example is the replace filter, whose purpose is obvious:

{{ "I like Twig."|replace({'like':'love', 'Twig':'you'}) }}

The following filters are built in:

  • date
  • format
  • replace
  • url_encode
  • json_encode
  • title
  • capitalize
  • upper
  • lower
  • striptags
  • join
  • reverse
  • length
  • sort
  • default
  • keys
  • escape
  • e
  • raw
  • merge

Most of these are self-explanatory. You can check the details in the documentation.

Control Structures Link

In templates, most of the operations you will be doing will be looping over a set of data (listing some items), sometimes accompanied by conditional statements (if … then). This is why Twig has implemented only for and if control structures, but they are quite powerful.

The for loop was presented in its simplest form in the previous section. Below are some more sophisticated examples.

Here is the code to iterate over a sequence of numbers:

{% for i in 0..10 %}
    item number {{ i }}
{% endfor %}

You can do the same with letters:

{% for l in 'a'..'z' %}
    {{ l }}
{% endfor %}

You can use variables and filters on both sides of the .. operator.

To access the keys of an array, you can use the following:

{% for k in myarray|keys %}
    key: {{ k }}
{% endfor %}

To access keys and values at the same time, you can use this:

{% for key, val in myarray %}
    key: {{ key }}, val: {{ val }}
{% else %}
    no items in the array
{% endfor %}

Notice the else block. It is rendered when the array is empty and no iteration takes place.

You may have noticed that the author of Twig was highly inspired by the behavior of the for structure in the Python language.

Important: you cannot use break or continue statements in the Twig version of the for loop. On the other hand, you do have access to a few useful variables inside the loop:

  • loop.index
  • loop.index0The iteration number. It is counted from 1 by default, so use index0 to make the index number start from 0.
  • loop.revindex
  • loop.revindex0This is the same as index0 but counted from the end of the loop.
  • loop.first
  • loop.lastThis is true if it is the first or last iteration in the loop.
  • loop.length

The if statement is almost the same as it is in pure PHP. You can use if, else and elseif tags. For example:

{% if user.role == 'admin' %}
    Hello, administrator!
{% elseif user.role == 'user' %}
    Hello, user!
{% else %}
    You don't have a role defined.
{% endif %}

As with the for loop, the operators in Twig are highly inspired by the ones in Python. For example, here we’ll check whether John is in the list of friends:

{% if 'John' in friends %}

Or you could use a predefined list:

{% if 'John' in ['Bob', 'Dave', 'John', 'Mike'] %}

To negate the value, use the word not, like so:

{% if 'John' not in friends %}

You may want to use tests in conditional statements, in addition to operators. For example:

{% if var is divisibleby(2) %}

Here are the tests that are built in:

  • divisibleby
  • none
  • even
  • odd
  • sameas
  • constant
  • defined
  • empty

This covers most of the basic syntax of Twig. To go deeper, you should read the extensive documentation.

Template Inheritance Link

As the creator of Twig states, template inheritance is the most powerful and important feature of Twig. It lets you define a main template as the base of other templates depending on the business logic. For example, you could define the base template below and save it to the file layout.phtml, in which you might want to define the basic layout of your website.

        <title>{% block title %}My page{% endblock %}</title>
        <div id="left-box">{% block leftbox %}This is the left box.{% endblock %}</div>
    <div id="content">{% block content %}{% endblock %}</div>

Then, by calling the template that extends layout.phtml, you will be able to add blocks containing only content in addition to the base template.

{% extends "layout.phtml" %}
{% block title%}{{ parent() }} - About me{% endblock %}
{% block content %}Lorem ipsum dolor sit amet.{% endblock %}

You can call the parent block using the {{ parent() }} function and extend it. If you don’t call a block (leftbox, in this example), its content will be left intact, as is the case with the parent template.

Template inheritance could help you create a flexible template architecture. Read the documentation to learn the details.

Incorporating Twig Into an Existing Project Link

Because Twig is so flexible an engine, there is no one specific way to incorporate it into your project. You just have to place the Twig library somewhere in your project and create directories for the cache and templates. The locations of all of these are up to you. Furthermore, you can define a PHP script as an entry point to your application, or include and instantiate the Twig object in every script in your project.

Conclusion Link

I hope you enjoy working with template engines such as Twig and that they increase your productivity and the cleanliness of your code. Good luck!

Further Reading Link

Here are some websites you might find useful:


Footnotes Link

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
  18. 18
  19. 19
  20. 20

↑ Back to top Tweet itShare on Facebook

Krzysztof Rakowski (@krzrak) has over twelve years of experience in designing and developing web applications in different technologies. Currently, he leads a team of Python wizards in the one of the top Polish interactive agencies - K2 Internet.

  1. 1

    Good intro and tutorial.
    Otherwise, I think MVC is useless for small websites. The point of this model is readability, maintainability, and “spaghetti code” performs much better on a small website. I’ve seen lots of dev using Zend for a fixe pages website, seriously, that’s useless.

    Go spaghetti, or go Dupral.

    • 2

      Krzysztof Rakowski

      October 17, 2011 4:45 am

      I disagree. If it is small project, the performance gain of “going spaghetti” is negligible and not worth the disadvantage of hard to maintain and potentially insecure code. Especially, if you give Drupal as an alternative :)

      • 3

        I can memcache using spaghetti code too and have same performance, in the end, its the knowledge of how to cache that counts for a small website and not what framework you use to build it?

      • 4

        Actually I disagree with spaghetti code, but MVC in many cases it is just too much for not only small projects, but larger ones too. All the MVC frameworks I’ve seen are so unnecessarily complicated.

        Also, aren’t most templating engines replacing things? Doesn’t this make the process slow? (except maybe with twig trying to compensate with compilation)

    • 5

      Dominic Watson

      October 17, 2011 3:29 pm

      It’s not about how big the project is. You should always assume that any project could get bigger. You start off with something small and as you continue it becomes an un-maintainable monster where you’re wishing you started off doing it properly. The more you do this and get setup the easier it is to do it again and again.

    • 6

      I guarantee I could write a site 10 times faster and with much better performance using a framework than you could with spaghetti code. I’m 100% confident in that because I’ve had to work with many codebases written with varying degrees of stupidity.

      You just could not be more wrong about the benefits of spaghetti code. With caching in a framework like Kohana, a framework is even faster than spaghetti code.

      “MVC” doesn’t mean “time-consuming”. The point of a framework is to take repetitive tasks (e.g. connecting to a database, selecting database, quering) and automating it (e.g. now the framework has a query() function that handles all of that automatically). Even with a “small site”, if you have code that is duplicated and you want to make even a small change, you have to remember all the places you wrote that same code. You’ll end up using a ton of search/replace, creating a lot of bugs, and being miserable.

      If you ever deal with code in your life, even if you’re not a programmer, you should look at this article:

      • 7

        Not if both space and time are constraints, you couldn’t. Caching, too, is a compromise, and you need to consider the realities of the environment your code is running in. There is a low level at which well-written “naked PHP” will outperform any framework, templating or otherwise. (Most of the “other people’s code” I’ve had to rewrite was to tune for shared hosting. As often as not, that means preprocessing framework-based source code to inline a lot of stuff for deployment.)

        • 8

          –Begin Mike’s Opinion–
          If the site has so little functionality that naked PHP would outperform a framework by any significant margin, it’s likely that it would do just fine in HTML only!

          If the site has enough functionality to need PHP, then it would be smart to use some well-tested base of code that helps you keep things DRY, like a framework or established CMS (like WordPress or Drupal).

          If the site has enough traffic or content to stress a shared hosting environment, then chances are it’s also large/complex enough to make it wiser to optimize for expensive developer time rather than hosting costs and an upgrade is in order.

          There just aren’t that many super simple but also high traffic sites.
          –End Mike’s Opinion–

          What frameworks are you cleaning up after? There are some that are much more bloated than others. Zend is 56 MB zipped! CodeIgniter and Kohana are tiny, weighing in at 3.79 MB and 2.04 MB uncompressed. They both seem to run great on shared hosting.

      • 9

        Framework is not a synonym for MVC. I prefer proven bit of code rather than framework. I totally agree to not reinvent the wheel. Take the (good) bricks and reuse it.
        @matt you’re wrong, MVC can be very small (and simple!) and it is all for strength and reusability.

  2. 10

    Just love Twig ;) Nice post

  3. 11


    Nice tutorial, what about cakephp as frameworks?

    Django is only for python, is’t?

    • 12

      Krzysztof Rakowski

      October 17, 2011 6:10 am

      Hi Julio. CakePHP and Django are web application frameworks – first is written in PHP, the latter in Python.
      CakePHP uses pure PHP in it’s templates. Django has it’s own templates’ syntax, very similar to Twig.

  4. 13

    I’m surprised Savant was not mentioned!

  5. 14

    I’ve been programming PHP professionally for 10 years, and through lots and lots of personal experience (I’ve tried all the major frameworks and CMS in different companies) I cannot emphasize enough how wrong it is to use a PHP template system like Smarty.

    As someone mentioned above, PHP already is a template system. You should *NEVER* use another one built on top of it. It’s pointless. It’s another thing to learn and, unless it “compiles” to PHP, it’s a totally unnecessary loss in performance.

    If you aren’t comfortable enough to work with PHP by itself, you aren’t a good enough programmer to developer a website and should either get better or hire someone to do it.

    Also, Zend is a mess/nightmare and is not much better than spaghetti code. The performance is abyssmal. If you’re a real programmer, use Kohana. If you’re not, use a CMS like WordPress for small sites or Drupal for bigger ones.

  6. 20

    You should really have a look at XSLT. Once you’ve got the basics it’s so mindbogglingly powerful, easily modularizeable and even fun to use!

  7. 21

    Smarty also compiles templates to the native PHP language. And caches them.

    • 22

      Krzysztof Rakowski

      October 17, 2011 6:05 am

      That’s true. As I have mentioned: “Many other frameworks (such as Twig and Django) have inherited some of the basic concepts laid down by Smarty.”

    • 23

      Any framework/template engine would have to “compile down to PHP”, since it relies on the PHP runtime for execution. The question is, how efficient is that PHP code compared to that generated by other, competing tools? Smarty may well still be seen as the default for new developers or legacy codebases, but I haven’t touched it professionally in at least 3 years.

      The last couple of books I’ve picked up on MVC development — as well as the one I’m writing — don’t even demonstrate Smarty; they only mention it as an alternative to the template engines being presented (RainTPL, Twig and Twig, respectively).

    • 24

      PHP is an interpreted language. Therefore, what these templating engines do is NOT compiling, but rather interpreting the template files into php script code. No compiling going on here.

  8. 25

    Why are you still using PHP short_tags? That’s a quick way to break an application.

    • 26

      Krzysztof Rakowski

      October 17, 2011 1:41 pm

      I used short tag only in one place, but I agree, that it might be better to use “< ? php echo" instead of "< ? =".
      I agree, that one should use long tags for the sake of portability, however, I don't see how using short_tags is "a quick way to break an application", especially if you have control over your server's php.ini.

      • 27

        Yeah, right .. IF you have an own server or access to the php.ini. But what is if you develop a theme, cms, plugin or similar for a customer who aint got that? Or simply build a theme that is going to be shipped elsewhere, with no knowing of the going-to-be conditions whatsoever?

        Aside of that, using the short tag variation is considered to be bad code writing style (common coding rules and such).

        cu, w0lf.

        • 28

          Using short echo tags is NOT considered bad style. In fact, starting from 5.4, short echo tags are now completely separated out from short PHP open tags, and is turned on by default.

          Sure, if you’re only working in a shared hosting environment where you have no control over your application, you’d be wise to make sure short echo tags are not used by default, but for those of us with control over our development environments, short tags are great.

  9. 29

    Tristan Reemer

    October 17, 2011 7:02 am

    PHP on itself is already a templating language. In my opinion, there is absolutely no reason for implementing another abstraction layer for templating.

    What exactly is the difference between the next 2 examples.

    {% for i in 0..10 %}
    item number {{ i }}
    {% endfor %}


    <?php for($i = 0; $i < 10; $i++) { >
    item number <?php echo $i; ?>
    <?php } ?>

    • 30

      The difference is an amount of visual noise. This may look fine in three lines example, but when you stare at pages long templates all day “PHP as templating language” does not cut it any more.

    • 31

      Krzysztof Rakowski

      October 17, 2011 1:47 pm

      Tristan, I see at least two differences:
      1. If your templates are coded by the designers, that have no experience in PHP, the risk of introducing bad code is much less, if you provide them with the limited set of easy to understand tags, not the full set of PHP functions.
      2. If you don’t trust the templates’ code (i.e. it’s uploaded by users etc.) you avoid introducing potentially dangerous code (PHP functions) to your applications. It’s like allowing users of your forum use BB Code instead of full HTML. Twig has great “sandbox” mode, which let’s you limit the allowed tags.

      • 32

        Why are you letting people who don’t know how to code, upload files to your server though?

        • 33

          Krzysztof Rakowski

          October 18, 2011 7:22 am

          Is it really so hard to imagine situation, when you want to have templates prepared by some people who are not skilled in PHP or whom you simply don’t trust?

          • 34

            Krzysztof Rakowski

            October 18, 2011 11:05 am

            @Nerd Alert: so imagine a situation, when you work with designers, who are uber-leet with HTML/JS/CSS but they are not skilled with PHP, and you don’t want to clean the code after them.
            Or other situation – you prepare CMS/blog/etc. engine, which allows users to upload their themes.

          • 35

            Yes it is… why would you ever let someone unskilled or untrustworthy to access your server? That’s the hardest situation I’d ever imagine.

          • 36

            @Krzysztof I am more than happy to give access to HTML/CSS devs, as they can create all the necessary clean code to keep my stuff organised well… but, I just don’t agree with giving people who have no idea how to use PHP or even a template language (to me @Tristan above is exactly what I was thinking) access to my server.

            I think that’s when I pass on the clean HTML to someone who knows what they are doing t update it.

            Don’t worry, not trying to have a go at you, I just think template languages are a bit horrible sometimes.

        • 37

          This happens all the time if you build websites for clients. You build a nice, pretty, spotless site or app and deliver it to your client. You give them their login, they start using it, and whatever isn’t absolutely bullet-proof gets destroyed in about 20 minutes. Next thing you know, client is on the phone asking why their site isn’t working.

      • 38

        Its not that designers should not see php code, there is a certain security risk in allowing native php templates in some cases. Take for instance a shared content management system, where users can create sites themselves. Native php is just too powerful. There is nothing stopping them from removing records from the database, listing other users content and such. A restricted layer that can only read data from objects is the simplest solution to the problem. See Liquid and LiquidDrops to understand the concept.

  10. 39

    Nice article, I had never heard of any of these template frameworks.

    I see you’ve acknowledged CakePHP above and since it uses pure PHP in its template files, I suppose it is not the best fit for readers of this article (especially if you are newer to PHP)

    However, I can’t help but take the time and comment on how much I LOVE and recommend it for its console functionalities including Bake which you execute through the terminal. Since Bake’s functionality effectively generates a mass of code for you to tweak to your desire based directly upon your MySQL setup, it takes a lot of the headaches out of the early development stages and caters to proper planning.

    Again, not a beginner concept, but I wish someone had drilled it into my head earlier what makes CakePHP so awesome for rapid development – I may have started with it sooner.

  11. 40

    Can you suggest any recursive php templating languages? Like you could have tags such as {{$tag}} inside of a tag {{$tag}} that is inside of {{$tag}} and so on?

    Yet to find one, was trying to make one but need some guidance.

    • 41

      You have yet to find one because whatever you’re trying to do can be done another way with existing tools.

      PHP has “variable variables”, so that if $name = ‘x’ and $x = 1, then $$name = 1. It also has arrays, which can be used in a similar way. You can have arrays within arrays within arrays.

  12. 43

    There is not only Zend-Framework as an alternative to spaghetti-code.
    I.e I use the framework yii – at last, I built an image – gallery / archive (also only a small project) and tested the performance with the tool gtmatrix – with hardly the default settings i made a good result and with some performance tuning i made a realy good result.
    and i can change things very easy – thats the main advantage of mvc – pattern. in spaghetti-code one small thing to change “can” be a huge thing…

  13. 44

    I can’t get why people promote Smarty so much. My experiences with it have been nothing but headache after headache. It’s pointlessly overcomplicated in my eyes.

  14. 45

    I don’t like those templates because they seem to incorporate too much logic.

    I use the archaic PHPlib template class, but I’ve re-written it to make it MUCH faster. the only thing it lacks is inbuilt caching. My template files do not contain any logic at all, only variables like {{VARIABLE}}

    • 46

      So your “template” system doesn’t do anything that PHP doesn’t do already, but it’s worse because it takes longer to type, doesn’t allow loops, and ostensibly must be str_replace()’d, which is totally unnecessary performance hit.

      Here’s how it would look in PHP:


      And here’s how yours looks:


      So what’s the point?

      • 47

        In PHP it would look like this: not just $variable.

      • 48

        The point is that logic is completely separate from presentation, as the template files only contain HTML (no PHP).

        That makes it very easy for front-end designers/developers to edit/create template blocks/pages.

        Everything has been much better + easier since I started using this architecture. Working very fast on some high-traffic sites.

    • 49

      Simple presentation logic such as looping over rows and such can (but usually shouldn’t be) in your templates; in most frameworks, there’s a better way to do it (like plugins).

      Business logic should never be embedded in presentation-level code — in any language or template system!

  15. 50

    Let me strike a blow for Smarty.
    In my opinion, with version 3, Smarty returned to be the best template engine. It’s very intuitive, expandable and the most concise in its syntax.
    It’s true, older versions were becoming quite a mess. But version 3 is completely rewritten (in PHP5), have a cool template inheritance system and a better parser that does not require javascript and CSS escaping anymore.
    About speed and performance, Smarty always compiles templates in native PHP code, so the template code has to be parsed only (and automatically) when template sources are modified. So, the template displaying overhead is quite small also for big projects.

  16. 51

    Timothy Warren

    October 17, 2011 8:09 am

    I agree with using PHP as the templating engine. Having dealt with Smarty, and an obnoxious “str_replace” templating engine, I don’t see the point in adding the complexity.

    The only benefit is visual, which is foolish, trading a small amount of template readability for a large amount of performance impact.

    • 52

      Care to provide benchmarks? It would be interesting to see how using e.g. Twig which gets compiled into the same native PHP is suffering compared to PHP.
      Visual benefit is not foolish it is very important: programmers tend so spend most of the time reading code, less modifying it and even less creating new one.

      • 53

        For the most part (leaving aside installations using HipHop, Phalanger or similar, which are rare on the ground, particularly in shared hosting situations — which is the typical deployment for SME) PHP doesn’t get “compiled” — it’s interpreted at run-time. The number of files fetched and parsed (as well as the string replacement, etc., required for rendering using a template outside of the code stream) does make a significant difference in run-time performance in both the time and space domains.

        That’s not to say that one couldn’t run a templated “meta source” through a pre-deployment processor to create a better-performing deployed PHP source, but that’s not what this article (or the templating solutions discussed) are all about. They’re best practices from a maintenance standpoint, but they do imply a compromise in performance — you’re likely to need quite a bit more server per user unless your site/app is small enough that you can cache everything.

        • 54

          PHP is compiled, it’s just compiled at runtime. If you manage your own server (or have a business-class host), your PHP installation should have APC, which will cache your compiled PHP code. In that case, the number/size of files you are including will be irrelevant.

          • 55

            This is not quite true. Having APC involved will reduce the “interpretation” massively, transforming source to opcode has to be done only once. But with default settings APC will still do a filemtime() [stat, disk I/O, slow] for each and every file you include. If you set apc.stat = 0; APC will not automatically reload changed source files, as it relinquished from that slow filemtime().

  17. 56

    “The {{% … %}} tag is used for flow-control statements, such as if and foreach;”

    I guess you mean “{ % … % }”.

  18. 57

    First of all, nice article! :-)

    Sometimes I am using a template engine for the development of a website or application and sometimes the templates are basic native PHP templates. I think both solutions have some good points to go with.

    The big advantages of using a template engine… (in my opinion) it should be more secure and less powerful then using native php code. Keep the view / template separated from the logic of an application. In this way it’s easier to learn a web-developer (without real programming skills) a “simple” language. And the chances are less that you will end up with crappy insecure code.

    On the other hand it’s probably always possible to mess up code :-)

    If you are using native PHP code as a solution you should be faster. But the learning curve might be more high-end since you have tons of possibilities :-)

    @Nils XSLT is also nice indeed! Unfortunately I don’t know that many people that are using it in projects right now.

    • 58

      Sebastiaan Stok

      October 18, 2011 12:08 am

      Oracle and PostgreSQL support native XML output, basically moving ‘some’ parts of the Models to the database.

      I’m not saying this will always work, but I have heard some great stories about it.

      Side note: If your making XML, never use plain strings since these are error prone.
      Always the Libs like DOMXML, SimpleXML etc.

      “If you’re a real programmer, use Kohana.”
      Why? You’re just saying something, Kohana (almost) only uses Static methods making Depency Injection almost impossible.

      Just because you like it, does not mean its good.

    • 59

      John Porter (@designermonkey)

      October 19, 2011 5:06 am

      Try the entire Symphony CMS community!

  19. 60

    I use ‘Spaghetti Code’ day in day out to make all of the web sites for my clients, and to be honest I prefer this way. Some of the sites I build are huge online communities, and I have experienced no ‘slow-down’ in development due to working this way. Each to their own really – there’s no wrong or right so long as the end result is a working product that is secure and runs efficiently.

    • 61

      Krzysztof Rakowski

      October 17, 2011 4:00 pm

      Try to imagine what happens, when your client wants to hire another programmer to work with your code.

      • 62

        We don’t develop a web site thinking ‘oh we better do it this way so when our client ditches us for someone else, the new guys will have an easier time working with our code’. We aim to secure our clients for the long-term by providing great work, so this hasn’t really ever been a problem or concern for us :)

        • 63

          Krzysztof Rakowski

          October 18, 2011 12:02 am

          OK, so imagine, that your business expands and you want to hire another programmers to work on your code.
          On the other hand, securing your job by producing hard to maintain code is very unprofessional.

          • 64

            Okay, so imagine that your business expands and you want to hire another programmer to work on your frameworked PHP code. They’re already a PHP expert, but oh wait, they now have to learn an entirely new framework just to add a simple add/edit/delete on a website. My point is that the overhead can (and most often does) exist in both situations, whether you use a framework or not. Any seasoned developer should be able to sift through either just fine. If you can’t read through “spaghetti code” or (generally) bloated framework code, then pick a new profession.

          • 65

            @Chris – You invalidate your own point: “They’re already a PHP expert, but… now they have to learn an entirely new framework” followed by “If you can’t read through spaghetti code or… framework code, then pick a new profession.” A decent developer should be able to do both, so it really comes down to comparing any drags on productivity that result from the use of each method, not on expectations you have of your developer. Furthermore, if you choose an established framework, there are many developers who already know it, thus eliminating that overhead.

            In my experience, there’s far more overhead in having multiple developers doing things their own way than in choosing a framework and asking them to use it.

            I have worked on several hundred websites, and I have not seen a single example of a substantial site using spaghetti code that worked well enough to stay spaghetti code.

          • 66

            Krzysztof Rakowski

            October 22, 2011 6:48 am

            @Chris: good developer’s time is too valuable to let him go through some undocumented spaghetti code.
            Most (good) frameworks are well documented and employ some common basic patterns, so good developer can work on any (good) framework without much hassle.

        • 67

          I agree, that is incredibly unethical. What if you change jobs, go out of business, or the client can’t pay you anymore?}

          I met a woman awhile ago who relied on her website to support her family, and when her site broke down after her old developer had left, she hired a new company to work on the site. The old developer had written spaghetti code for the same reasons as you, and she couldn’t afford to have it fixed and went out of business.

          Also, you’re probably happy with spaghetti code because you’ve never coded another way. Life is much easier if you code properly with separation of concerns, which is why people have decided to call it the “proper” way to code.

    • 68

      Your way is just unprofessional.

    • 69

      Justin St. Germain

      October 18, 2011 12:48 pm

      pfft, that’s ameture, i use manicotti code. :P

      manicotti code: nicely wrapped up objects with clean code and lots of comments
      (this is just the definition i just came up with, so yeah, just go with it)

  20. 70

    @Steve: …If you’re a real programmer, use Kohana. If you’re not, use a CMS like WordPress for small sites or Drupal for bigger ones…

    And all the programmers, who use other frameworks aren´t real programmers, or what?

    • 71

      Let me rephrase that.

      If you’re a real programmer and you don’t use Kohana already (probably because you’ve never heard of it), then you will be delighted and relieved to use a framework as efficient, well-designed, and elegant as Kohana. In short: if you’re not using it and you know how to program, you should switch.

      I know a lot of good programmers who don’t use it, but it’s usually because they haven’t had the time, energy, or opportunity to try it out.

  21. 72

    Has anyone ever tried this template engine:
    Can someone share some experience on that?

  22. 73

    Stephen S. Musoke

    October 18, 2011 3:54 am

    Would you consider Zend_View a template language coz it sure looks and works a lot like Twig given that both Symfony and Zend_Framework both have MVC frameworks

  23. 74

    When I saw header of this article I thought: Boooring, why even write about MVC structure, it’s BASICS OF WEBSITE PROGRAMMING and everyone knows it.
    But when I got to the comments section I was really surprised by the number of guys saying that template engines are BAD. So I think this article was really needed.

    MVC gives you clean and editable code. When I see spaghetti code to edit, I automatically double the stake for my work.
    That’s why I hate systems like Joomla, WordPress and all this non-template engine software – it’s just not professional! These systems were made without template engine to give non-programmers tools for design.

    Using template engines is like using DAO classes for database management of your products, offers etc. objects.
    I use spaghetti code only for short scripts which aren’t integrated with website.

    Some guys mentioned about performance degradation.
    You better show some benchmarks because I think that whole template engine operations will consume less time than database operations in average CMS ( every CMS takes around 20 queries to load a static page)

    • 75

      There is always a trade-off between organization and efficiency for code. However, with servers as powerful as they are today, it is extremely cheap to scale. On the other side of that trade-off, it is extremely expensive (i.e. time-consuming) to work on disorganized code. So yes, there is a tiny, negligible performance cost for MVC frameworks vs spaghetti code, but there’s a substantial (and eventually unaffordable) cost for working on disorganized code.

  24. 76

    David Hancock

    October 18, 2011 5:40 am

    I’ve been meaning to try out Twig for quite some time now, this article might just push me to set aside some time and get on with it. Thanks!

  25. 77

    Kacey Keleher

    October 18, 2011 6:25 am

    I’ve been developing for nearly ten years, and I’ve created my own MVC that I am constantly updating to run better, and faster. Even if someone wants to use “spaghetti code,” they should consider how much easier they will make things on themselves if they at least incorporate some sort of a structured outline for their code. It’s much nicer if a few years later an old client calls and wants something updated, or has discovered an error, and you know exactly where to look because everything is organized and manageable.

  26. 78

    Gabriele Romanato

    October 18, 2011 6:38 am

    As usual, an interesting and poignant article spoiled by the same old debate on the best template system in PHP. The best template system in PHP is the template system which works at its best for you. That is, the system which makes your site/application run as fast as you want. Names are meaningless, facts are everything: so if you find out that you can use your homemade template system better than Smarty or everything else, then use it. Nobody could blame you for that. If your users are happy and your clients satisfied, then you’ve find a good solution. But be aware of the fact that your solution may not work well for other developers. People are different. That’s why we have billions of web sites on the WWW instead a few elected ones. :-)

  27. 79

    I really don’t get you guys. All of you (except a few) are TOTALLY against spaghetti code. Really, you should be programmers and clearly are smart enough not to interpret ‘spaghetti code’ as a website where the same code is copy/pasted again and again giving yourself a headache when changing something.
    I was developed a huge website based on no framework but with a large amount of functions.
    Still spaghetti in your opinion because well, I’m not using MVC or any other framework but please don’t tell me that spaghetti automatically implies dumb programming skills.

  28. 80

    I am using Latte templating engine included in Nette Framework
    It is very similar to Smarty, but much more advanced.

  29. 81

    I’m a designer myself and I have a team of designers and programmers in our web development team. We design about 40 small and large websites a year. The designers are fully autonomous at setting the websites all by themselves.
    We do it all in Smarty and the programmers dont ever touch the interface (html / smarty/CSS/JS).
    It works. It´s clean, fast, simple.

  30. 82

    I love the coding tutorials you post these days. :) They are really awesome and so much better than round-ups etc. other sites post. Please keep publishing stuff like that!

  31. 83

    And where is

    Blitz templates, fast and powerful PHP template engine for very big internet projects

    Use less CPU and is faster

  32. 84

    Models are far more than simple database access objects. They are, in fact, the entire core logic of your application. They describe how objects in your system interact (for example, if you have a blog post object which can “own” a set of comment objects made against that post, then deleting the post should cause the object representing the post in question signalling all the comments owned by that post to delete themselves as well.

    I’ve seen too many projects where all the application logic was implemented in the controllers, leaving the models as little more than a database access layer. This is a bad design choice because now you can’t reuse your models without using big chunks of the controllers as well. We don’t want fat controllers, this isn’t Thomas the Tank Engine.

  33. 85

    I’ve been programming in PHP for 11 years now. Still find some good old spaghetti with functions and classes the way. MVC for me it is too much fragmented and for team work as mentioned before, I think its equally difficult to understand others code when you get yourself in a situation that you’ve to pick it up from middle.

    Classes and functions work wonderfully for me, plus seems faaaast.
    But there are many ways to cook dinner.

    • 86

      I’ve been working in PHP for about the same amount of time as you, and I disagree with some of your points, but I love this:

      “But there are many ways to cook dinner”

      There are many coding methodologies and frameworks, and you can build a good site or app with most of them IF you do it right. Usually the “doing it right” part outweighs the “choice of methodology/framework” part.

      I will say that the most important thing when working with other developers is to do things the same way–as long as everyone is writing code in a well-defined free-form or framework way, things will come together.

  34. 87

    All this talk about PHP templates and frameworks when you all know we will all be converted to writing Ruby with the use of Rails or Cucumber before too long. Although I do agree with Gordon that too many developers are trying to write their models as purely database access objects. I think most PHP frameworks try to push the idea of using models solely for that purpose by how their tutorials and documentation is written.

  35. 88

    Looks like advertisement for me … never heard about COMPER Template Parser, yet?

  36. 89

    Hi everyone!

    I’m a php programmer for a few years now and I want to learn the MVC thing. Can You advise me some books or tutorials where to start? I know the basics of it but i should start at the very beginning right? So please tell me some good source where I could start!
    Some theory first maybe and then some examples.
    Is this Twig good for a starter? My other colleague uses Yii and it looks really nice.
    Thanks for all the help!

    • 90

      Try CodeIgniter … Lightweight framework that helps you understand MVC and I’m sure you’ll love it (then try COMPER Template Parser, pretty awesome lib.)!


  37. 91

    Something I’ve noticed through my professional career as a PHP developer: Developers that rely on frameworks and templating systems to do all the heavy lifting tend to be inexperienced or write crappy code.

    Instead, more focus should be put on writing clean & lean code. Practice the KISS principle. I don’t condone the use of a templating system on-top of PHP. As others have mentioned, PHP itself is a templating system. Designers should be able to understand simple structures like if statements, for loops, and displaying variables on a page. If they can’t understand that, well, then your job (the programmer) should be setting up the page.

    This is how most companies I’ve worked at operate.

    • 92

      That’s interesting, my experience as a professional PHP developer has been quite the opposite–the pros use frameworks and those who try to write everything from the ground up are usually the ones churning out sub-par code. I won’t say that my experience is universal, however–I believe there are good coders in both camps.

      Clean and lean code doesn’t exclude frameworks. In fact, frameworks are usually optimized and can help code to be cleaner and leaner. If your framework isn’t optimized, it’s time to switch to one of the many that is!

      Template systems have pros and cons–they can be simpler for designers and more mistake-proof, but at the cost of an extra layer of code. For example, If you give a designer access to PHP and they misplace a single character, they can take down the whole site. If you give them a template system and they mess it up, then it’s more likely that only the output of that portion of the template gets broken.

      • 93

        This article is a bit dated, but, even Rasmus Lerdorf (creator of PHP) thinks frameworks are a poor choice.


        You can do some things fairly quickly using frameworks, but your performance isn’t going to be that great. Generally speaking most frameworks are garbage if being judged purely on a performance standpoint. Furthermore, if your PHP framework has a bug (Look at the zend bug tracker – at last check – bugs only – 1200+!) then good luck hoping for a fix or being forced to fix the issue yourself.

        Anyway, It doesn’t matter how fast or how stable they get. Even though that article is from middle of 2008, it still stands true today. If a framework tries to layer it’s own junk or sub-scripting language on top of PHP (already slowed down by the fact that it itself is a scripting language), you’re (probably) just doing it wrong.

        That said, yeah, PHP frameworks are great when they’re done for small projects or special-purpose stuff. It depends on the situation IMO. But generally, your brain is better off avoiding them. You’ll learn more and you’ll write better code than if you just used them all your career.

        • 94

          Dave, the following isn’t directed specifically at you but was inspired by our conversational thread.

          I think that many people in this thread are lumping frameworks and template engines in together, and they’re not the same.

          I think many are ignoring the development/use cases where custom code or a framework may be more appropriate than the alternative.

          I’d say that a lot of the anti-framework people in these comments seem to be talking about the most bloated examples they can think of (Zend!) so they can try and prove their point. I would also say the pro-framework people are thinking of the lightest-weight, most efficient cases they can think of.

          Custom coded systems tend to become more framework-like–WordPress, Drupal, Facebook, and so on began as custom but standardize more and more as they go on. Framework-based systems tend to begin relying on the framework but move toward having more and more custom pieces as they develop.

          Anyone who utterly disregards the side he doesn’t personally prefer is being closed-minded and is missing out on a chance to improve.

          Hopefully everyone can take another look at all the options and walk away having learned something new that will improve how they work.

  38. 95

    Wonderful tutorial, in my mind MVC is better option for small or big projects, because its security, reusability, maintenance and data control. I use Codeigniter, is a big app framework, can work with own libraries and methods easily. I really hate the “spagetti mode” is very tedious for update it.

    Thanks again…

    Add: Coding in php pure is better option for everythings :)

  39. 96

    I’ve been coding front/back-end for almost 10 years, html,javascript/jquery,php,etc.

    i honestly can’t wrap my head around the mvc pattern, i understand what it’s supposed to do, but it all seems so disjointed to have 3 files using the same variables but stored all voer the place or in dif directories.

    what i pretty much do is keep my .php files filled with almost 90% html and just include my php function library, and i’ll call the function in the template file from my included library.

    so if i need to update, i view the source of the template to see which functions are producing what, and then i just edit my functions which are all stored in one place or maybe 2 files.

    the main poroblem i run into is if i only need to slightly change the output, then i’d need seperate functions or write the function so that it branches based on parameters passed to it, and this works fine for me, all my functions are in one or two files and i can just re-use the library on other projects – plus there is very little php code in the templates which mostly contain html.

    but i’d very much like to learn the mvc pattern if someone can provide a nice tutorial without comparing every framework, and especially explaining which each part does thoroughly.

    for me encapsulting my php into functions means they don’t fight with each other since you can’t the same function declared twice, and it keeps the php in my templates very minimal as i am mostly just making function calls – i can easilly re-use different comnbination of functions in seperate template files – and most coders can see that my template is referring to a function and just go update that function or clone it an rename it slightly.

    so in a way my php stays hidden away in my function library and i can create multiple templates based on which functions are needed for each template, and i can clone a function and simply rename it to something more suitable if i need similar functionality, but if this happens i will often break the function into many smaller functions that can be used together, so it’s
    more like using many smaller objects in one bigger object, but i lose the ability to have another programmer understand my code readily since it is not based on a common framework, but at least the php in my templates is very minimal and the functions can easily be updated or cloned or broken into smaller functions that each do part of the work if you find that one function is doing too many things.

    any good tutorials for someone new to mvc that really explains it clearly before launching deeply into one framework or the other before we can understand the concepts thouroughly?

  40. 97

    wow, I’m really shocked how much ant-framework people are there :) I started writing “spagetti”, then created a small custom MVC framework, which now supports a pretty big project really well. Now I mostly use Kohana, and it is damn awesome.

    MVC is simple, there are tons of various tutorials, you just have to google and start learning. Later, when you’ll look back at your code, you’ll think – “yeah, they were right, what was I thinking?”

    And yeah, template enginges suck.

  41. 98

    Hi, it is a good article on templating frameworks, actually i don´t use any of these frameworks, i used to write spagetti code, then i start doing things like this:

    structure: HTML
    presentation: CSS
    behavior of app: jQuery

    So, for this part there are 3 files, .html, .css and .js

    To avoid mix the server-side code in the HTML, i rely totally in jQuery Ajax requests, so the entire app request and sends the data to the server with ajax requests using JSON.

    I think that this could not be the proper way to do it, thinking on those people without javascript disabled on their browsers.

    I think this is the only fall down to this approach, because jQuery will handle the cross-browser issues.

    This has turn my code experience to a new level, more structured files, more clean and easy to maintain.

    I´m only worried about the progressive enhancement and graceful degradation.

    Also i would like to learn to make things the MVC way, so if someone can give me a reference of a good and easy start to MVC with PHP will be of much help.


    • 99

      It’s interesting that you adopt this method to structure your code, is it mainly that you deal more with the frontend rather than backend?

  42. 100

    PHP is a template system. No need to create complicated, redundant and exaggerated template engines. Take for example WordPress and my CMS ( They both don’t use complicated stuffs and yet they both can parse anything you throw at them (user-defined functions).

    Also, template systems/engines requires you to learn their language which is redundant and a waste of time.

  43. 101

    Shame no link to download any of the Twig code is available… would be interesting to re-write it in good old php+html and see how different they really are, how well they perform against each other in benchmark test, and more importantly which is more readable.

    I think already know the answer, after all the way a I read it twig is just a layer on top of php which is converted back to php with a few perl shortcuts added in the mix.

    Being able to squeeze all the code in to a single 80 char line because you learnt all the perl shortcuts makes for some seriously ugly code.

  44. 102

    i am new user of PHPTAL i am not able to provide value to text box using PHPTAL please help me how to do this.



↑ Back to top