PHP code example of prinsfrank / object-resolver

1. Go to this page and download the library: Download prinsfrank/object-resolver 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 / object-resolver example snippets


 declare(strict_types=1);

readonly class LogInRequest {
    public function __construct(
        #[SensitiveParameter] private string $email,
        #[SensitiveParameter] private string $password,
    ) {
    }
}

 declare(strict_types=1);

readonly class LogInController {
    public function __invoke(LogInRequest $logInRequest){
        // Handle authentication
    }
}

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,
                static function (ObjectResolver $objectResolver, ServerRequestInterface $serverRequest) use ($identifier) {
                    $requestData = match ($serverRequest->getMethod()) {
                        'GET' => $serverRequest->getQueryParams(),
                        'POST', 
                        'PATCH', 
                        'PUT' => $serverRequest->getParsedBody(),
                        default => [],
                    };

                    return $objectResolver->resolveFromParams($identifier, $requestData);
                },
            )
        );
    }
}

final class ObjectResolverServiceProvider implements ServiceProviderInterface {
    #[Override]
    public function provides(string $identifier): bool {
        return $identifier === ObjectResolver::class;
    }

    /** @throws InvalidArgumentException */
    #[Override]
    public function register(string $identifier, DefinitionSet $resolvedSet): void {
        $resolvedSet->add(
            new Concrete(
                $identifier,
                fn () => new ObjectResolver(Casing::camel, Casing::snake)
            )
        );
    }
}