Change the name of a Symfony autowire alias

669 views Asked by At

I'm using Symfony 5.3 and the Symfony RateLimiter bundle.

For this to work, a method should be called by:

public function root(Request $request, RateLimiterFactory $authenticationApiLimiter)
{
}

A RateLimiterFactory requires that the variable be called $authenticationApiLimiter to correctly autowire. However, this project uses the snake_case variables standard.

How do I either alias or change this?

Thanks

1

There are 1 answers

0
Cerad On BEST ANSWER

I like most of Symfony's design but they tend to get a bit carried away when it comes to automatically naming things. The best full time solution really is to follow the Symfony standard and just live with it. However you can use bind to change the argument name if you really want to.

# config/services.yaml
services:
    # default configuration for services in *this* file
    _defaults:
        autowire: true      # Automatically injects dependencies in your services.
        autoconfigure: true # Automatically registers your services as commands, event subscribers, etc.
    
    # named alias    
    Symfony\Component\RateLimiter\RateLimiterFactory $anonymous_api: '@limiter.anonymous_api'

class DefaultController extends AbstractController
{
    #[Route('/', name: 'default')]
    public function index(RateLimiterFactory $anonymous_api): Response
    {
        return $this->render('default/index.html.twig', [
            'controller_name' => 'DefaultController',
        ]);
    }
}

Instead of a named alias you could also just use a bind. I think the alias is bit more specific but they both work.

To figure out the service id, start by creating a new 5.3 project, installing symfony/rate-limiter and then copying the rate_limiter.yaml file from the docs to config/packages.

bin/console debug:container RateLimiterFactory

 Select one of the following services to display its information:
  [0] Symfony\Component\RateLimiter\RateLimiterFactory $anonymousApiLimiter
  [1] Symfony\Component\RateLimiter\RateLimiterFactory $authenticatedApiLimiter
 > 0
Information for Service "limiter.anonymous_api"
===============================================

 ---------------- -------------------------------------------------- 
  Option           Value                                             
 ---------------- -------------------------------------------------- 
  Service ID       limiter.anonymous_api                             
  Class            Symfony\Component\RateLimiter\RateLimiterFactory  
  Tags             -         

The limiter.anonymous_api is the key. You can use the service in the named aliases.