PHP code example of prinsfrank / container

1. Go to this page and download the library: Download prinsfrank/container library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

prinsfrank / container example snippets


private const REQUEST_CLASSES = [
    // list of classes
];

public function provides(string $id): bool {
    return in_array($id, self::REQUEST_CLASSES, true);
}

public function register(mixed ...): void {
    foreach (self::REQUEST_CLASSES as $requestClass) {
        $this->container->add(
            $requestClass, 
            fn() => $objectResolver->resolve($requestClass)
        )
    }
}

final class RequestDataProvider implements ServiceProviderInterface {
    public function provides(string $identifier): bool {
        return is_a($identifier, RequestData::class, true);
    }

    public function register(string $identifier, DefinitionSet $resolvedSet): void {
        $resolvedSet->add(
            new Concrete(
                $identifier,
                fn (ObjectResolver $objectResolver) => $objectResolver->resolve($identifier),
            )
        );
    }
}

class FooApiServiceProvider implements ServiceProviderInterface {
    public function provides(string $identifier): bool {
        return $identifier === FooApi::class;
    }

    public function register(string $identifier, DefinitionSet $resolvedSet, Container $container): void {
        $resolvedSet->add(
            new AbstractConcrete(
                $identifier,
                static function (Environment $environment, ClientInterface $client) {
                    return new FooApi($environment->get('FOO_API_KEY'), $client)
                }
            )
        );
    }
}