简体   繁体   中英

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 :)

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');

Static functions in Controllers doesn't seem like a very Symfony way of doing things. Services and dependancy injection tend to be the way to go as it at once decouples the functionality from a single controller AND makes it more easily reusable. Think this method will probably also sharpen your logic regarding how you build that service. Symfony best practise is for light controllers, so any heavy business logic should be moved out to a service.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM