Monday, November 25, 2019

Lite Framework in PHP

I noticed something bad: when I create a small static website, instead of using the Framework, I rather write it from scratch. It's probably so, because I'm a performance freak and that extra weight of the Framework is bothering me.

I tried to create a minimal version in the past, but it still wasn't what I was looking for.

So, I decided to cut the Framework into layers: the base layer will be good for static websites and simple APIs, but lightweight enough to offer mostly benefits of handling modules, forms, CORS, errors and other basic stuff.

The next layer will add sessions, messaging and authentication, and the final layer will add config, internationalization, multi-app and multi-site support and the rest of all the QetriX magic.

Using Converters, Components and DataStores in Lite Framework will be encouraged, but not enforced. I want no dependencies, my goal is to point a web server to a single script, write a single module and voilà.

Monday, November 18, 2019

PHP templates

I've always knew PHP started as a templating engine and in its core it still is one. When I tried to figure out an easy way for implementing templates for HTML pages, I remembered this and looked around for such solutions.

I totally forgot PHP allows to mix HTML and PHP so effortlessly:

  1. <?php if (...) { ?>
  2. Hello, world!
  3. <?php } ?>

If you don't want PHP in your template, all you have to do is create some semantic markup, that you can easily replace with PHP code:

  1. {{ IF XXX }}
  2. Hello, world!
  3. {{ END IF }}

Then you generate a PHP script from your markup-flavored HTML template and keep it as cache, that changes only if you change the template. It's much faster, because you don't parse it all the time and you can even take advantage of OPcache.

For generating the PHP script you can use regular expressions, but simple explode works equally well:

  1. $ifs = explode("{{ IF ", $template);
  2. foreach ($ifs as $if) {
  3. $cond = explode("}}", $if, 2)[0];
  4. }

In the code above I separated the entire template by {{ IF and then every element again by }}. Now I have the condition I can evaluate. But I never use eval, not even for hardcoded strings. I either implement some custom condition handling, or keep it as a piece of valid PHP code.