A special thanks to James Halsall for some excellent tips in tapping into Symfony events through kernel listeners.

His article explains how to create a service to trigger on certain events, this is related to the FOS User Bundle but the same pattern applies to most events in your Symfony project.  Click here to read the entire article with explanations and example code.


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.


The Symfony documentation is getting better, but it still lacks more detail, which is why I’ve been collecting helpful tips and snippets here.  According to the Symfony docs, by default, the “redirectToRoute()" method performs a 302 (temporary) redirect, so in order to specify a 301 (permanent) redirect, you can add the third argument in this method within your controller and logic that would trigger a redirect.

public function indexAction()
{
    return $this->redirectToRoute('http://www.belchamber.us/page-to-redirect', array(), 301);  // 301 is where you can also specify 302
}

 


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 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.