I usually end up implementing my own very small class that couples with a database table to create my own caching system.  It’s very easy to create one that way and it’s organized and has the extra benefits of not being files and so can be easier to maintain and access, be removed upon expiration with a simple query to the database.

That said, Symfony has a very thorough caching system, and other developers may have noticed an option called “cache:warmup”.  Of course, to warm up a cache usually refers to prepping the system and pre-populating the cache so the first visitors don’t get hit with a performance penalty because, well, they were the first poor shlubs to access a certain page that hadn’t been cached yet.  Kind of like trailblazers for the rest.

Anyway, I wanted to find out more, so I visited this site and found a very thorough explanation.

http://blog.whiteoctober.co.uk/2014/02/25/symfony2-cache-warmup-explained/

Sensio Labs, who is the company behind Symfony, has made an incredible tool, but I find their online resources aren’t nearly as thorough as Zend.  More real world examples ranging in complexity could easily quadruple their cookbook, but it’s needed.  With such a powerful and diverse PHP framework and so many tools, there is plenty of room to help build the community and create more common practices along with concrete examples.  To dig into Symfony, I suggest visiting their website at http://symfony.com/doc/current/cookbook/index.html.

Cache warming in Symfony.  Another mystery revealed!


In Symfony, you can set the parameter “invalid_message” in your form types.

For example:

class FooShortlistChoiceType extends AbstractType {
    protected $em;

    public function __construct(EntityManager $entityManager)
    {
        $this->em  = $entityManager;
    }

    public function buildForm(FormBuilderInterface $builder, array $options) {
        $fooTransformer = new FooToStringTransformer($this->em);
        
        $builder
            ->add('yourField', 'text', array('invalid_message' => 'Invalid message pertaining to this form field here.'))
            ->get('yourField')->addModelTransformer($fooTransformer);
        
    }

    public function getParent() {
        return 'choice';
    }

    public function getName() {
        return 'fooShortlist';
    }
}


For more about Data Transformers and what they’re used for, visit the Symfony Cookbook:  http://symfony.com/doc/current/cookbook/form/data_transformers.html


In Symfony, making a service means different classes and their functions can be called on as needed from the controller without cluttering up your controller and allowing you to separate useful code that can be called on from other places later.  That’s modularity, efficiency and the DRY principle (Don’t Repeat Yourself).

Here is a simple pattern to get you started in adding a service entry and then an example is provided how to call on the custom class.  This calls on a special class of methods meant to deal with processing payments, including cleaning credit card input of any characters except digits.

In this example, the file “ProcessPayment.php” is saved in the bundle’s /Form directory where I suggest making a special folder called “Handlers”.  Handlers, as in “form handlers,” actually signifies the opposite of what a repository does in Symfony.  A repository is meant to only accept parameters and return values, like a list of the 5 most current blog posts, etc.  Also, you don’t have to save your form handlers in a “/Handlers” folder like I have, but I find that helps organize code and segregate these more sensitive form functions being saved within the “/Forms” folder of the bundle.

Just a tip I find useful in remembering where things go.  When you first start Symfony, the file organization can be a little confusing.

In bundle services.yml:

parameters:
  process_payment.class:  Main\MainBundle\Form\Handlers\ProcessPayment
    process_payment.transport:  cleanCcInput  # This line is not necessary to work

services:
  process_payment:
    class:  "%process_payment.class%"
      calls:
        - [cleanCcInput,['']]

Code to call on service from controller:

$cc_full_num_cleaned = $this->get('process_payment')->cleanCcInput($cc_full_num);

It would be helpful if there were more solid examples of Symfony projects for those learning this powerful framework. If any developers have any recommendations, I would appreciate it, not just for me, but some friends and colleagues who are interested!

– Aaron Belchamber


Symfony2 and Twig work great together.  Symfony is an advanced PHP framework that is growing in popularity.  If you are a company that relies on rapid application development and need a stable and secure development and production environment, Symfony is one of the top choices to consider.  More on Symfony another time, we’re talking Twig today.

What is Twig and why should I learn it?

Twig is straight forward and has a pretty quick learning curve.  Twig is a templating system that is intuitive and really does help reduce the amount of code while keeping your views neat and more importantly, functionally separate from your business logic, which is always what good “V”s — the “V” in “mVc” — is supposed to do.  Twig isn’t a language, it’s a set of rules and constructs based on simple programming patterns that introduce only 3 new tags:  {% do something %}, {{ show something }}, {# comment on something #}.  These tags help you create editable blocks based on a base template.  If you use Dreamweaver templates or some other template system, adapting to Twig and the concept of extending and overriding base templates will be nothing new.  It’s powerful because it’s simple to follow the cascading logic that so much of the web works from.

Basics behind Twig templating

The concept behind templates and cascading style sheets are all the same.  For simplification, let’s say you have a base template that can have anything in it, including the base HTML code for a basic page in your website.  We’ll represent that as a simple-to-follow pattern where each number represents a different important part of the webpage, like the header, metatags in the header, top menu, sidebar, footer, etc.  However you want to logically group your pages into manageable blocks, so let’s say your template is based on a simple construct:  “1 – 2 – 3 – 4 – 5 – 6 – 7 – 8 – 9”.  When you create a new template based on this base template, you only tell the system what’s different and show the rest as is.  So in simplified terms if your new template has a command that says “5=A”, the new output from a template will look like this:  “1 – 2 – 3 – 4 – A – 6 – 7 – 8 – 9”.  Basically, instead of writing out all the code for each page over-and-over, you practice the DRY (Do Not Repeat Yourself) principle and use a template to override the parent, or base template.

In your new child template, you can use powerful commands to change a lot from the base with little code.  In your child template, you can say things like “change all dashes to tildes” — and one command can change your template to the new pattern “1 ~ 2 ~ 3 ~ 4 ~ A ~ 6 ~ 7 ~ 8 ~ 9”.  You get the point, templates are all about making the output of your views easier to reuse and maintain.  Not to mention they’re not nearly as scary to non-coders who have to poke around and update little things in your website, you know they can’t alter global variable values or do other things that could alter the business logic of your web application(s).

Twig provides rules and structure that consolidate mainly view functions based on the most common PHP capabilities, like iterators — a way to “loop” through values and show a list on screen quickly and easily.  A way to sort or filter your output without sending a new query and waiting for a response from your database.  It can reduce requests and server loads by being more efficient with your website’s resources.  Twig also works best with PHP Storm IDE since it has great live validation and helpers.  PHP Storm is a potent combination for serious PHP web developers using Symfony, Twig, and LESS as well.


I first learned about Doctrine, the PHP-based database project, in 2008.  At the time I didn’t understand why would you need an intermediary layer between your applications and your database, which is what Doctrine is — a “DBAL” — Database Abstraction Layer.  Why can’t everything just talk to each other directly?  Years went by and though I learned some things about Doctrine and Object Relational Mappers (ORM)s I didn’t have a solid grasp of how to use it in a practical, real-world application.  No company thought it was necessary, they preferred to keep all their databases and direct querying because that’s all they knew.

Why make something that’s already complicated even more complicated?  At least that was the questions I heard.  In actuality, wouldn’t it be easier to visit a foreign country with someone who could translate, speak the language, and knew their way around?  A pretty good analogy — that’s what Doctrine does for databases.

For most companies and applications I developed web solutions for, there really was no immediate need for this kind of solution.  They weren’t ready to scale this way — at least with their systems and data.  Let the web application talk directly to the database, we’ll worry about growth later.

Just getting a company to consider using a database at the time and dedicating time to not only design it, but maintaining it, was quite a hurdle!

It takes time, thought, and real work to set up a database properly and to make sure all the systems in the company that pour information into it and feed information from it are all working optimally, so when you start talking to non-technical people about the importance of their database and how it affects everything throughout their entire system, it’s hard to calculate the costs and the ROI from investing in such improvements.  Remember it affects every person who accesses this company’s computer system or website, so it wouldn’t be difficult to help realize the opportunity costs incurred by not acting!

Think of using ORMs for your company like “Database Insurance”

It’s not that it’s very complicated. Your company outgrows its small rented office and needs to find a real building.  Without having an ORM to protect your company’s database, it’s like finding out you can’t move — all your valuable equipment is just too big and heavy and if you move it, you will destroy it all.  You’re stuck.  Pretty inconvenient wrench thrown in your growth plans…

Web Developer:
“Look, CEO Bill, your customers are your most important asset, but understanding their wants and needs is the key to growing profits.  That means you need information about them, how to reach them, how to inspire them to act — your information and systems all rely on a database that needs to collect all vital customer, product, marketing, and company information that can work together to maximize sales outcomes because information and marketing working together will not just keep your business afloat, it will help you reach new heights.”

CEO Bill smiles admiringly:
“Well that’s right, for the most part.  But customer service, relationship building and word-of-mouth all existed before a database.”

Web Developer:
“Well, you didn’t store information about your customers on a computer, but you kept records, they were on paper and probably stacked in boxes that took a long time to sift through to make any sense out of it.  Imagine all the information that was never read that could have helped you make better decisions faster to help improve sales — all the opportunities for new ideas and innovation never saw the light of day because all that information was collected but painful to retrieve.  Wouldn’t you want to have more useful information with less hassle?”

CEO:
“Sure.”

Web Developer:
“Imagine if you were stuck with an antiquated database system that broke a lot and didn’t give you much useful or reliable information, not to mention the fact that it didn’t help you automate a lot of your systems that cost you hundreds, possibly thousands of hours in manual labor every year.  If we take the time and deliberately plan your needs and design a system, database and infrastructure that can support your company needs well into the future, you will save more money in efficiencies and make more money in new revenue and marketing opportunities than doing nothing.”

Don’t get entangled in “web development strangulation”

Because improving your data and systems will almost always result in much higher efficiencies and profits, even in the short run, you need a web developer who will be honest with you.  You also need to stay far away from those who call themselves web developers who write code to entrap “customers for life”.  You know the symptoms, perhaps you’ve been a victim of it yourself.  Why does it take so long to make a small change to your website, Intranet portal, or some backend report?  If you often ask or hear this question, this is a symptom of concern for your company — you are wasting time and energy and probably have wasted a lot of time, energy and money getting in the mess you’re in now — “entangled code”, you are an unknowing victim of “web development strangulation.”

First of all, no real web developer worth their salt wants to keep going back to the same project over and over and fixing things they intentionally sabotaged just to keep their job.  I’d die of boredom!  Yet, many developers create complex monsters for three reasons, and three reasons only:

  1. They don’t know what they’re doing, so they “wing-it” and go on Google and slap things together until they work.
  2. They intentionally design in an over-complex way to ensure that no one else could grasp or understand, much less fix or easily replace code they’ve written in the past.
  3. They really don’t know what they’re doing.

The real test is if a web developer writes code and acts like they don’t want to see this project again so they spend enough time designing, thinking, planning and writing code properly so they can move onto more challenging and exciting projects.  Just be sure they showed you enough of the plans and the thought that went into the design of your new systems and databases and be sure to ask what their plans are if the company out grows the system or if they decide to change database systems.  If they look at you horrified, chances are they haven’t been exposed to ORMs.  Mention that you insist on future compatibility and scalability and ask them if they do not recommend using an ORM in your system now, how would they plan on accommodating your company’s plans for growth later?

Using an ORM isn’t even that much more effort on the front end, but knowing you everything you need is neatly ready for scaling and portability is another positive in your company’s asset column that will inevitably bring you more revenue into your P & Ls.

– Aaron Belchamber