I'm attempting to write my own wrapper around request parameters, so I can reuse the same parameter class throughout the system (e.g. in commands), where the request stack is not available. Currently, several services have a request wrapper injected, which itself has the RequestStack
injected.
What I hope to achieve is to, in services.yml
, define that the service App\Util\Parameters
should be injected with the values of $queryString
and $content
from the below example:
class SomeService {
public function __construct(Symfony\Component\HttpFoundation\RequestStack $stack)
{
$request = $stack->getCurrentRequest();
...
$queryString = $request->getQueryString();
$content = $request->getContent();
...
So, in services.yml
, I'm hoping to do something like:
# psuedo-config..!
App\Util\Parameters:
arguments:
$content: ['requestStack.currentRequest.getContent']
$queryString: ['requestStack.currentRequest.getQueryString']
Given the following class:
namespace App\Util;
class Parameters {
public function __construct(protected mixed $content = [], protected string $queryString = "")
{
...
My hope is that in other parts of the system, where the RequestStack
is not available, I could do something like the following to override the injection,
$params = new Parameters(['foo' => 'bar']);
but in cases where the Parameters
service is injected, the values would instead be populated from the request.
CodePudding user response:
You would need to create a service factory.
App\Util\Parameters:
factory: '@App\Util\ParameterFactory'
And then the factory:
class ParameterFactory {
public function __construct(private RequestStack $stack)
{}
public function __invoke(): Parameters {
$request = $this->stack->getCurrentRequest();
$queryString = $request->getQueryString();
$content = $request->getContent();
return new Parameters($content, $queryString);
}
}