PHP code example of gravatalonga / king

1. Go to this page and download the library: Download gravatalonga/king 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/ */

    

gravatalonga / king example snippets

  


class Dumb implement ServiceProvider
{
    public function factories(): array
    {
        return [
            'random' => function() {
                return rand(0, 10);
            },
            'math' => function($random) {
                return 1 + $random;
            },
            'other' => [self, 'getOtherFactory']
        ];
    }
    
    public function extensions()
    {
        return [
            /**
             * @var $other is a previous entry
             */
            'other' => function (ContainerInterface $c, $other) {
                return $other + 1;
            }
        ];
    }
    
    public function getOtherFactory(ContainerInterface $container)
    {
        return $container->has('random') ? $container->get('random') : null;
    }
}
  

$app = new App();

$app->get('/get', function(Request $request, Response $response) {
    $response->getBody()->write("Hello World");
    return $response;
});

$app->run();
  


class HelloServiceProvider implement ServiceProvider
{
    public function factories(): array
    {
        return [];
    }
    
    public function extensions()
    {
        return [
            RouteCollectorInterface::class => function (ContainerInterface $c, RouteCollectorInterface $route) {
                $route->get('/get', function(Request $request, Response $response) {
                    $response->getBody()->write("Hello world");
                    return $response;
                });
                
                return $route;
            }
        ];
    }
}