Skip to content

Allow Inject own variables in EntityValueResolver #20030

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 3 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 41 additions & 0 deletions doctrine.rst
Original file line number Diff line number Diff line change
Expand Up @@ -781,6 +781,47 @@ variable. Let's say you want the first or the last comment of a product dependin
): Response {
}

If you need to get other information from other services, you can also inject variables in your expression
thanks to the ``VariableInjector`` service. By default only user is injected ::

#[Route('/product/{id}/comments')]
public function show(
#[MapEntity(class: Post::class, expr: 'repository.findBy({"author": user.id}, {}, 10)')]
iterable $posts
): Response {
}

If you need other services in the Expression you can alias original service ::

#[AsAlias(id: 'doctrine.orm.entity_value_resolver_variable_injector')]
class VariableInjector implements EntityValueResolverVariablesInjectorInterface
{
public function __construct(private TokenStorageInterface $tokenStorage, private MyService $myService)
{
}

public function getVariables(): array
{
return [
'user' => $this->tokenStorage?->getToken()?->getUser(),
'my_variable' => $this->myService->getMyVariable(),
];
}
}

and getting your variable in MapEntity Expression ::

#[Route('/product/{id}/comments')]
public function show(
#[MapEntity(class: Post::class, expr: 'repository.findBy({"author": user.id, "other": my_variable}, {}, 10)')]
iterable $posts
): Response {
}

.. versionadded:: 7.2

The variable injector was introduced in Symfony 7.2.

MapEntity Options
~~~~~~~~~~~~~~~~~

Expand Down
Loading