Symfony’s Service Container allows you to manage object dependencies efficiently. Understanding it is key to writing maintainable applications.
Defining Services
Services are PHP objects managed by the container. You define them in YAML, XML, or PHP configuration.
# config/services.yaml
services:
App\Service\Mailer:
arguments:
$transport: '@App\Service\Transport'
Injecting Services
Constructor injection is preferred:
class UserNotifier {
public function __construct(private Mailer $mailer) {}
public function sendNotification(User $user, string $message) {
$this->mailer->send($user->getEmail(), $message);
}
}
Autowiring
Symfony supports autowiring, automatically injecting dependencies based on type hints:
services:
App\Service\:
resource: '../src/Service'
autowire: true
Conclusion
Mastering services and DI in Symfony improves modularity, testability, and maintainability of your PHP projects.
Comentarios (3)
Autowiring examples make this much easier to understand.
Excellent coverage of services, thanks!
Thanks for sharing.