Search code examples
phpsymfonycode-injection

Dependency Injection vs Static


I am learning symfony framework and I am wondering : if I need something like an helper (for example) is it better to make a service (to do a dependancy injection into my controller) or is it better to create a static function. What are the pros and cons of each method.

Thank you in advance :)


Solution

  • This is a very significant question regarding the best way to add reusable libraries that does very specific processes.

    The Symfony way is make it a service and register it in the service container.

    <?php 
    
    namespace Acme\MainBundle\Services;
    
    class MobileHelper
    {
        public function formatMobile($number)
        {
            $ddd = substr($number, 0, 2);
            $prefix_end_index = strlen($number) == 11 ? 5 : 4;
            $prefix = substr($number, 2, $prefix_end_index);
            $suffix = substr($number, -4, 4);
    
            return sprintf('(%s) %s-%s', $ddd, $prefix, $suffix);
        }
    
        public function unformatMobile($number)
        {
            $number = preg_replace('/[()-\s]/', '', $number);
    
            return $number;
        }
    }
    

    Then on services.yml

      mobile.helper:
        class: Acme\MainBundle\Services\MobileHelper
    

    Then you can use it in your controller like:

    $mobileHelper = $this->get('mobile.helper');
    $formattedMobile = $mobileHelper->formatMobile('11999762020');