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:
Your comment and opinion are very much appreciated.
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!
symfony2 service is not a singleton.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With