I
I
Igor2020-01-28 18:33:51
symfony
Igor, 2020-01-28 18:33:51

Symfony, who knows how to map a value from a Request?

Good evening!

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.
        bind:
            $images_directory: '%app.images_directory%'
            $lang: '%blabalabla%' # Господа, обратите внимание!


Note that $lang will appear as an argument in the controller or service.
My question is how to map the value from Request to this variable?

method in the controller.
... 
  public function add(Request $request, EntityManagerInterface $manager, $lang)
  ...

Answer the question

In order to leave comments, you need to log in

1 answer(s)
B
BoShurik, 2020-01-28
@IgorPI

In general, no way.
Workaround: via value object:

class Locale
{
    /**
     * @var string
     */
    private $value;

    public function __construct(string $value)
    {
        $this->value = $value;
    }

    public function __toString()
    {
        return $this->value;
    }
}

class LocaleFactory
{
    /**
     * @var RequestStack
     */
    private $requestStack;

    /**
     * @var string
     */
    private $default;

    public function __construct(RequestStack $requestStack, string $default)
    {
        $this->requestStack = $requestStack;
        $this->default = $default;
    }

    public function create(): Locale
    {
        if ($request = $this->requestStack->getMasterRequest()) {
            return new Locale($request->get('locale', $this->default));
        }

        return new Locale($this->default);
    }
}

services:
    App\Locale\Locale:
        factory: ['@App\Locale\LocaleFactory', 'create']

Accordingly, use not as a scalar value
public function add(Request $request, EntityManagerInterface $manager, Locale $lang)

Action Argument Resolver / ParamConverter is also an option, but will only work for controllers.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question