diff --git a/README.md b/README.md index d451ecc..71fbdd7 100644 --- a/README.md +++ b/README.md @@ -128,6 +128,21 @@ class MyService } ``` +You can also use the `#[Target]` attribute: + +```php +use MongoDB\Client; +use Symfony\Component\DependencyInjection\Attribute\Target; + +class MyService +{ + public function __construct( + #[Target('second')] + private Client $client, + ) {} +} +``` + ## Database Usage The client service provides access to databases and collections. You can access a database by calling the diff --git a/src/DependencyInjection/MongoDBExtension.php b/src/DependencyInjection/MongoDBExtension.php index 3b4ce85..ff23ce3 100644 --- a/src/DependencyInjection/MongoDBExtension.php +++ b/src/DependencyInjection/MongoDBExtension.php @@ -78,6 +78,7 @@ private function createClients(string $defaultClient, array $clients, ContainerB // Allows to autowire the client using the name $container->registerAliasForArgument($serviceId, Client::class, sprintf('%sClient', $client)); + $container->registerAliasForArgument($serviceId, Client::class, $client); } // Register an autowiring alias for the default client diff --git a/tests/Functional/Attribute/AutowireClientTest.php b/tests/Functional/Attribute/AutowireClientTest.php index cd2ce86..7fc6b9c 100644 --- a/tests/Functional/Attribute/AutowireClientTest.php +++ b/tests/Functional/Attribute/AutowireClientTest.php @@ -53,6 +53,9 @@ public static function autowireClientProvider(): iterable /** @see AutowireClientController::viaNamedClient() */ yield 'via-named-client' => ['/autowire-client/via-named-client', self::CLIENT_ID_SECONDARY, self::DB_CUSTOMER_GOOGLE, self::COLLECTION_USERS]; + + /** @see AutowireClientController::viaTarget() */ + yield 'via-target' => ['/autowire-client/via-target', self::CLIENT_ID_SECONDARY, self::DB_CUSTOMER_GOOGLE, self::COLLECTION_USERS]; } /** diff --git a/tests/TestApplication/src/Controller/AutowireClientController.php b/tests/TestApplication/src/Controller/AutowireClientController.php index 820c45b..ef88184 100644 --- a/tests/TestApplication/src/Controller/AutowireClientController.php +++ b/tests/TestApplication/src/Controller/AutowireClientController.php @@ -24,6 +24,7 @@ use MongoDB\Bundle\Tests\Functional\Attribute\AutowireClientTest; use MongoDB\Bundle\Tests\Functional\FunctionalTestCase; use MongoDB\Client; +use Symfony\Component\DependencyInjection\Attribute\Target; use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\Routing\Annotation\Route; @@ -69,6 +70,16 @@ public function viaNamedClient( return new JsonResponse(); } + #[Route('/via-target')] + public function viaTarget( + #[Target('secondary')] + Client $client, + ): JsonResponse { + $this->insertDocumentForClient($client, FunctionalTestCase::DB_CUSTOMER_GOOGLE, FunctionalTestCase::COLLECTION_USERS); + + return new JsonResponse(); + } + #[Route('/with-unknown-client')] public function withUnknownClient( #[AutowireClient(client: 'foo-bar-baz')]