Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony: Service Container VS Static Method

Let's take this as example, I have a method call validateDateTime in a Validator class. This function is just simple as to check if the date time is in the required format.

namespace MyApp\Util;

use \DateTime;

class Validator {
    public static function validateDateTime($dateTime, $format = 'Y-m-d') {
        $d = DateTime::createFromFormat($format, $dateTime);
        return $d && $d->format($format) == $dateTime;
    } 
}

Before I learned Symfony, I always use static method for the ease of the use of function if the function has to be shared across the application.

After I have learned Symfony, I know that Symfony has a very power full feature which is service container to perform the same convenience to access the function that will be used across entire application.

My questions are:

  1. What are the pros and cons of using static method vs service container
  2. In Symfony best practice, is it recommended to use service container over static method if I want to achieve same purpose (Function that sharing across entire application).
  3. In what situation, when and why, we need to use static method

Your comment and opinion are very much appreciated.

like image 514
overshadow Avatar asked Apr 01 '17 01:04

overshadow


People also ask

What is Symfony service container?

In Symfony, these useful objects are called services and each service lives inside a very special object called the service container. The container allows you to centralize the way objects are constructed. It makes your life easier, promotes a strong architecture and is super fast!

Are Symfony services Singleton?

symfony2 service is not a singleton.

What is Factory in Symfony?

Symfony's Service Container provides multiple features to control the creation of objects, allowing you to specify arguments passed to the constructor as well as calling methods and setting parameters.


1 Answers

Don't use static methods if you may need -in future- another implementation of the functionality you're writing. Static method are meant to be "static", not to be changed or extended.

Service "IoC" container is used to make your code easier to be changed or extended by decoupling components and inversing dependability between them, you can add new implementations or change existing ones without the need to do any changes to any dependent components.

like image 99
irza Avatar answered Oct 25 '22 09:10

irza