Symfony service container helps keep code organized, functions segregated, and your controllers lean and mean!

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:

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

    class:  "%process_payment.class%"
        - [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

About Author:

Senior Cloud Software Engineer and 25+ years experienced video production, video editing and 3D animation services for a variety of global clients including local video production here in Jacksonville, Florida.

Leave a Comment

Your email address will not be published. Required fields are marked *