Skip to content

@Autowired annotation #39054

@Microtribute

Description

@Microtribute

Description
It would be nice if we had @Autowired annotation like Spring. Rather than injecting services via the constructor, we could use @Autowired annotation to make it even simpler. Check out the examples below:

Example
Currently we're injecting services via the constructor.

namespace App\Manager;

use Psr\Log\LoggerInterface;
use Symfony\Component\Routing\Matcher\UrlMatcherInterface;

class TrafficManager
{
    private UrlMatcherInterface $urlMatcher;
    private LoggerInterface $logger;

    public function __construct(UrlMatcherInterface $urlMatcher, LoggerInterface $logger)
    {
        $this->urlMatcher = $urlMatcher;
        $this->logger = $logger;
    }

    public function match(string $url)
    {
        try {
             $this->urlMatcher->match($url);
        } catch (\Throwable $e) {
            $this->logger->error($e->getMessage());
        }
    }
}

If we had @Autowired annotation, we could make this simpler eliminating the need of creating a constructor.

namespace App\Manager;

use Psr\Log\LoggerInterface;
use Symfony\Component\Routing\Matcher\UrlMatcherInterface;
use Symfony\Comonent\DependencyInjection\Annotations\Autowired;

class TrafficManager
{
    #[Autowired]
    private UrlMatcherInterface $urlMatcher;
    
    #[Autowired]
    private LoggerInterface $logger;

    public function match(string $url)
    {
        try {
             $this->urlMatcher->match($url);
        } catch (\Throwable $e) {
            $this->logger->error($e->getMessage());
        }
    }
}

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      pFad - Phonifier reborn

      Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

      Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


      Alternative Proxies:

      Alternative Proxy

      pFad Proxy

      pFad v3 Proxy

      pFad v4 Proxy