Created
May 1, 2022 15:41
-
-
Save cspray/d6c87dd14bec6a0923da84a3e4ddde1b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
use Cspray\AnnotatedContainer\Attribute\Service; | |
use Cspray\AnnotatedContainer\Attribute\Inject; | |
use Cspray\AnnotatedContainer\ParameterStore; | |
use Cspray\Typiphy\Type; | |
class MySecretParameterStore implements ParameterStore { | |
public function getName() : string { | |
return 'secrets'; | |
} | |
public function fetch(Type $type, string $key) : mixed { | |
// Something you'd implement to retrieve the value from your secrets store | |
return fetchFromVaultOrAwsSecretsOrSomewhereElseSafe($key); | |
} | |
} | |
#[Service] | |
class SomeApiClient { | |
public function __construct( | |
#[Inject('my-api-key', from: 'secrets')] | |
private readonly string $apiKey | |
) {} | |
} | |
$compiler = ContainerDefinitionCompilerFactory::withoutCache()->getCompiler(); | |
$containerDefinition = $compiler->compile( | |
ContainerDefinitionCompileOptionsBuilder::scanDirectories(__DIR__ . '/src')->build() | |
); | |
$containerFactory = new AurynContainerFactory(); | |
$containerFactory->addParameterStore(new MySecretParameterStore()); | |
$container = $containerFactory->createContainer($containerDefinition); | |
// The value returned from they 'my-api-key' passed to MyParameterStore::fetch will be injected | |
$myClient = $container->get(SomeApiClient::class); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment