I like to reuse code as much as possible and if there’s underyling data in something I’ll use again, I’ll put that data in some extractable form in an EAV (Entity, Attribute, Value) database table so I don’t need to maintain the data anywhere except one place.

So in the example below where the variable $jsonText is being assigned, I actually have a method called getFormChoices(‘states’) that pulls this $jsonText automatically, from anywhere.  In Symfony, the getFormChoices() is a method I use in a base repository class that all other repositories extend and therefore inherit automatically.  This is efficient since certain higher-level global functions are all accessible and maintained in a single “Base Repository” class.

<?php

$jsonText='{"AL" : "Alabama", "AK" : "Alaska", "AZ" : "Arizona", "AR" : "Arkansas", "CA" : "California", "CO" : "Colorado", "CT" : "Connecticut", "DE" : "Delaware", "FL" : "Florida", "GA" : "Georgia", "HI" : "Hawaii", "ID" : "Idaho", "IL" : "Illinois", "IN" : "Indiana", "IA" : "Iowa", "KS" : "Kansas", "KY" : "Kentucky", "LA" : "Louisiana", "ME" : "Maine", "MD" : "Maryland", "MA" : "Massachusetts", "MI" : "Michigan", "MN" : "Minnesota", "MS" : "Mississippi", "MO" : "Missouri", "MT" : "Montana", "NE" : "Nebraska", "NV" : "Nevada", "NH" : "New Hampshire", "NJ" : "New Jersey", "NM" : "New Mexico", "NY" : "New York", "NC" : "North Carolina", "ND" : "North Dakota", "OH" : "Ohio", "OK" : "Oklahoma", "OR" : "Oregon", "PA" : "Pennsylvania", "RI" : "Rhode Island", "SC" : "South Carolina", "SD" : "South Dakota", "TN" : "Tennessee", "TX" : "Texas", "UT" : "Utah", "VT" : "Vermont", "VA" : "Virginia", "WA" : "Washington", "WV" : "West Virginia", "WI" : "Wisconsin", "WY" : "Wyoming"}';
$jsonArr=json_decode($jsonText,true);

echo $jsonArr['VT']."<br/>";   // will return "Vermont"

// Build an HTML form SELECT pulldown with state acronyms as keys and the state names spelled out as display values:

$out="<select name='states'>";
foreach($jsonArr as $key=>$val){
    $out.="<option value='$key'>$val</option>";
}
$out.="</select>";

echo "Select your state: $out";

Please feel free to use parts or all of this script below in your own PHP projects.  Some old school developers might remember 1999 hard-coding every state as an HTML SELECT option — yet, there are still web developers out there that spend time remaking these over and over.  Your company pays for this inefficiency in a big way — projects don’t get completed as fast as they could or should, for one.  Do you suspect your web department is complacent and inefficient?  Ask them what they are doing to be efficient and reduce code maintenance later.  If your web developers don’t have a clear answer, chances are they haven’t adapted in 5 years and your systems and code will reflect this apathy.


I recently ran into an issue where I found I was creating a new user profile system for different systems and then it occurred to my:  DRY.  DON’T REPEAT YOURSELF.  Yet, in the bustle of activity I realized there was too much in common with these user profiles to rewrite the code.

So why not extract the user-related code and put it all in its own bundle for easier maintainability?  After all, in Symfony, it’s a breeze working between bundles, from one bundle you can call code from other bundles.  It was a “duh” moment, to say the least.

So how do you move some code you wrote that works to its own bundle?  Well, it took me less than 5 minutes to move 6 entities, 7 controllers and their supporting code like routing and update to the new bundle.

Step #1:  Go to your command line and type:    “app/console  generate:bundle”

I went through the Symfony tool and called it “UserBundle”.  Symfony will automatically create all the base and template files and folder structure for you new User Bundle.

Step #2:  Now, find all code that you already wrote and move it all to your new bundle following the same folder structure.

Step #3:  Do a search and replace all paths to your old bundle where the “namespace” and “use” declarations are and replace with the path to your new User Bundle.

Step #4:  Update your routes with the new paths, where applicable to make sure they are pointing to your new bundle’s controllers.

Step #5:  Clear your cache with “app/console ca:cl –env=prod”  then “app/console ca:cl”

Step #6:  Type in the URL that matches the path that will execute the controller code with the “app_dev.php” debug in the URL and test for errors.

Step #7:  Congratulate yourself for having the foresight to using a PHP framework, imagine the logistics if you wanted to move your code from some home-grown system what pitfalls you could have encountered.  Aren’t Symfony web developers just luckier than the plain old PHP developer variety?  Well, we’re luckier because there are tools and helpers already waiting for us so we can focus on writing code that creates solutions, not writing the code that helps us write the code to create solutions.  All you companies with your own Web Development department — are you getting this yet?!  If not, your loss.  Literally….


Here’s how you can allow different search engine bot crawlers if you prefer to address them individually.  There might be some crazy reasons why which I try to explain below.  For some companies, it seems web developers often don’t dev to create new web assets, they dev to squeeze any remaining SEO juice from their old assets.  Always diminishing returns when you measure the opportunity cost of not spending time and resources moving forward, but instead looking back.

SetEnvIfNoCase User-Agent .*bing.* search_robot
SetEnvIfNoCase User-Agent .*google.* search_robot
SetEnvIfNoCase User-Agent .*yahoo.* search_robot
SetEnvIfNoCase User-Agent .*bot.* search_robot
SetEnvIfNoCase User-Agent .*ask.* search_robot

Order Deny,Allow
Deny from All
Allow from env=search_robot

Here are some more .htaccess SetEnvIf & SetEnvIfNoCase Examples from Apache’s website.

PHP Logic for detecting different search engine crawlers

You may want to redirect your content to be customized for different search engine bots to repair certain SEO issues that you may encounter.

Here is the Search Engine Directory of Spider Names

if(stristr($_SERVER['HTTP_USER_AGENT'], "googlebot")){

    // what to do -- change "googlebot" to other spiders in list
}

For certain instances where some how a server that was supposed to be locked down was inadvertently crawled by a search engine, you don’t want to open your entire site for all crawlers, here’s a way you can open your site to confirm your site ownership file by the crawler and perhaps disavow content if you don’t have anything better to do than massage your site’s SEO and squeeze every drop of juice from it.

<html>
<head>
<META NAME="ROBOTS" CONTENT="NOINDEX, NOFOLLOW">
<title>Web Development is a finite resource</title></head>
<body>
Does quality content matter any more?
</body>
</html>

 


Here’s how you can check if a session in Symfony was started:

if ($this->get('session')->isStarted()){

    // Session has been started, so do stuff here
}

Not a big fan of session variables, but used for non-sensitive session data, I think sessions are still useful.  After all, if you only want certain behaviors on your website tailored to a customer apply only while their browser is open on your site, this is an efficient way to pass certain settings and values along with a small footprint since all sessions go to garbage upon the visitor’s browser being closed.

 


By bootstrapping a Symfony project I am referring to creating a ready-to-go basic software package from which to build any projects from.  This also does include Twitter’s awesome Bootstrap libraries as well.

New project requires a well-designed database first

The first thing I usually do with a new Symfony project is design the database.  I use Oracle’s free tool called MySQL Workbench.  Here is a screenshot of a basic database design.  Once I go through the database and document how it will work, I then migrate the table model to the database where it creates the actual tables.

While it may take days to design the database first, this is by far the most critical step because your Symfony project, like most websites, depends on the database to perform properly.

Copying an existing Symfony project or phase of project or start from scratch?

So while this is going on I then would set up a new instance of Symfony on the website.  For first-timers, you need to do it a few times and get used to being able to have the framework’s tools write a bunch of code already for you!  Simply follow the instructions in the Cookbook on Sensio Lab’s Symfony website — a newest feature now is the Symfony installer which you will now need to install first before executing the few other command line prompts.

It’s fast and easy and all the Symfony files will be loaded on your website in the standard folder structure ready to go.  You can move folders around later and if you already did this on a local dev, you can just copy the entire folder to another site.  As an alternative, before you dev’d that project, you could use the .git repository and use the first commit as your bootstrap as well and simply check out those files from the repository.

There are many ways to deploy Symfony and since Symfony’s meant to be modular, Sensio claims it’s flexible and easy to deploy and I find it is most the time.

Essentially any already deployed Symfony project can serve as your next bootstrapped project.  Just don’t copy over anything dealing with “cache” folders or “cache” in the file names.

During initial Symfony set ups, depending on your host and server machine on occasion I would run into some file permission issues or directives in the php.ini or .htaccess files that are prohibited with certain hosts, but this is the exception and not the rule.

Composer – get to know your new friend

You’re not going to get very far if you don’t learn Composer.  It’s pretty easy how it works but it helps you keep all your software dependencies in line so things don’t break later.  Composer is your friend so take 10 minutes and learn up on what it is and does!

In case you were wondering, you can install it on your server through the command line, it’s usually better if you are logged in as the root user:

$ curl -sS https://getcomposer.org/installer | php

Bootstrapping your Bootstrap Symfony Project

Besides the FOSUserBundle, which now looks like it comes with the newest Symfony package, I usually install Braincrafted’s Bootstrap Bundle automatically since I use it for so many projects.  You can always not use a bundle from a vendor, but it’s usually a foregone conclusion I will be needing it.  So follow the instructions how to install the Bootstrap Bundle or simply go to your Symfony folder and add these three requirements to your composer.json file:

"require": { ...
  "braincrafted/bootstrap-bundle": "dev-master",
  "twbs/bootstrap" : "dev-master"
  "jquery/jquery":  "1.11.*"
}

By the way, jQuery’s pretty common and works well with Bootstrap themes, so you need to throw this into the composer.json file after your “requires” list:

 "repositories": [
        {
            "type": "package",
            "package": {
                "name": "jquery/jquery",
                "version": "1.11.1",
                "dist": {
                    "url": "http://code.jquery.com/jquery-1.11.1.js",
                    "type": "file"
                }
            }
        }
    ],

Then on the command line update all your Composer dependencies by typing in:

php composer.phar update

It also just updated my Symfony from 2.6.3 to 2.6.9, so I’m curious if I’ll run into any issues.  You’ll know if you do usually right away you will see 500 errors blowing up or blank pages (yikes) and what you need to do is Google frantically or roll back version in your composer.json file until the errors go away.  Lesson here?

Never ever ever run Composer updates on a live site, always do it on a staging server and test it, then test it again, then ask end users to test your staging again before going live!

Everytime you update your Composer dependencies, you must CLEAR YOUR SYMFONY CACHE!

Do save yourself the frustration and navigate to your Symfony install on your site, usually inside “public_html” and automatically type in  “app/console  ca:cl”  then “app/console ca:cl –env” in that order on your server.  This will clear the cache, sometimes it doesn’t make sense, but do it.  This is just the abbreviated commands for “cache:clear”.

Commit your Barebones Symfony so you have a snapshot

Now, since you’re using a local computer as a dev server and hopefully not the one you’re coding on because running VM on the same machine is asking for performance frustration later — you can just grab the entire site, pull it down, it’ll take 3 minutes.  I use PHP Storm for my IDE and already have it connected to my BitBucket account so after grabbing it all, I commit it and push the code to BitBucket and mark it with “INITIAL COMMIT” and I usually leave a note like “Bootstrap template” so I know it’s a quick way I can have Symfony-ready site to dev later.

Need help?  Feel free to contact me!

 

– Aaron Belchamber

www.AaronBelchamber.com