简体   繁体   English

依赖注入与静态

[英]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. 我正在学习symfony框架,我想知道:如果我需要类似帮助器(例如)的东西,最好是制作服务(对我的控制器进行依赖注入)或创建静态函数更好。 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. Symfony的方法是将它作为服务并在服务容器中注册它。

<?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 然后在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. 控制器中的静态函数似乎不是一种非常Symfony的做事方式。 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. Symfony的最佳实践是针对轻型控制器,因此任何繁重的业务逻辑都应该转移到服务中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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