Hyperf Nano

repository·master·Indexed 19 days ago

https://github.com/hyperf/nano

A minimal, zero-config distribution of Hyperf for building high-performance applications using a single PHP file and a closure-based API. It features a simplified AppFactory for initialization, integrated routing, middleware, exception handling, and support for custom CLI commands, processes, and crontabs. Nano includes a ContainerProxy to provide DI container access within closures and supports the Swow engine and hot reloading via hyperf/watcher.

Tokens
10.1K
Snippets
50
Records
51
Agent score
65%

What's inside hyperf-nano

  1. Use the DI Container and ContainerProxy

    master

    Nano provides access to a Dependency Injection (DI) container. You can manually set instances using $app->getContainer()->set().

    Important Convention: In all closures managed by Nano (routes, middleware, exception handlers, etc.), $this is automatically bound to an instance of Hyperf\Nano\ContainerProxy. You can use $this->get(ClassName::class) to retrieve services from the container.

    <?php
    use Hyperf\Nano\ContainerProxy;
    use Hyperf\Nano\Factory\AppFactory;
    
    class Foo {
        public function bar() { return 'bar'; }
    }
    
    $app = AppFactory::create();
    $app->getContainer()->set(Foo::class, new Foo());
    
    $app->get('/', function () {
        /** @var ContainerProxy $this */
        $foo = $this->get(Foo::class);
        return $foo->bar();
    });
    
    $app->run();
  2. How the ContainerProxy works in Nano

    master
    In all closure callbacks managed by $app, the $this context is automatically bound to an instance of Hyperf\Nano\ContainerProxy. This allows you to access the DI container and Hyperf components directly within your routes, middleware, or commands using $this->get(ClassName::class) or accessing properties like $this->request.
  3. Quickstart with Nano

    master

    Nano is a minimal Hyperf distribution designed for zero-config, single-file applications. You can create a complete server by using AppFactory::create() and defining routes via closures.

    To start the server, run your entry file with the start command.

    <?php
    use Hyperf//\nuse Hyperf\Nano\Factory\AppFactory;
    
    require_once __DIR__ . '/vendor/autoload.php';
    
    $app = AppFactory::create('0.0.0.0', 9051);
    
    $app->get('/', function () {
        $user = $this->request->input('user', 'nano');
        $method = $this->request->getMethod();
    
        return [
            'message' => "hello {$user}",
            'method' => $method,
        ];
    });
    
    $app->run();
    php index.php start
  4. Enable Hot Reloading with hyperf/watcher

    master

    To enable hot reloading, install hyperf/watcher and configure the watcher settings within $app->config(). Use the php index.php server:watch command to start the watcher.

    composer require hyperf/watcher
    <?php
    
    use Hyperf\Nano\Factory\AppFactory;
    use Hyperf\Watcher\Driver\ScanFileDriver;
    
    require_once __DIR__ . '/vendor/autoload.php';
    
    $app = AppFactory::createBase();
    $app->config([
        'server.settings.pid_file' => BASE_PATH . '/hyperf.pid',
        'watcher' => [
            'driver' => ScanFileDriver::class,
            'bin' => 'php',
            'command' => 'index.php start',
            'watch' => [
                'dir' => [],
                'file' => ['index.php'],
                'scan_interval' => 2000,
            ],
        ],
    ]);
    
    $app->get('/', function () {
        return 'Hello';
    });
    
    $app->run();
    php index.php server:watch
  5. Use Swow Engine

    master

    Nano supports the Swow engine. To use it:

    1. Install the Swow engine via composer: composer require "hyperf/engine-swow:^2.0".
    2. Use AppFactory::createSwow() instead of create() to initialize the application.
    composer require "hyperf/engine-swow:^2.0"
    $app = AppFactory::createSwow();
    
    $app->get('/', function () {
        return 'Hello World';
    });
    
    $app->run();
  6. Quick Start with Nano

    master

    Nano allows you to build a Hyperf application using a single PHP file. Use AppFactory::create() to initialize the application, define routes using closure-style methods, and call $app->run() to start the service.

    To start the server, run the PHP file with the start command:

    <?php
    use Hyperf
    anoactory\AppFactory;
    
    require_once __DIR__ . '/vendor/autoload.php';
    
    $app = AppFactory::create();
    
    $app->get('/', function () {
        $user = $this->request->input('user', 'nano');
        $method = $this->request->getMethod();
    
        return [
            'message' => "hello {$user}",
            'method' => $method,
        ];
    });
    
    $app->run();
    php index.php start
  7. Configure Hyperf Components

    master

    You can configure Hyperf components (like Database) by passing an array to $app->config(). This allows you to define settings like database hosts, ports, and credentials within your single-file application.

    $app->config([
        'db.default' => [
            'host' => env('DB_HOST', 'localhost'),
            'port' => env('DB_PORT', 3306),
            'database' => env('DB_DATABASE', 'hyperf'),
            'username' => env('DB_USERNAME', 'root'),
            'password' => env('DB_PASSWORD', ''),
        ]
    ]);
  8. Initialize and run a Nano application with App

    master

    The Hyperf\Nano\App class is the primary entry point for bootstrapping a Nano application. You instantiate it by passing a PSR-11 ContainerInterface. You can then configure routes, middleware, and other components before calling run() to start the application server.

    Note that when using Closures for routes, commands, or processes, Nano automatically binds them to the application's BoundInterface, allowing you to access application context within those closures.

    use Hyperf\Nano\App;
    use Hyperf\Context\ApplicationContext;
    
    $container = ApplicationContext::getContainer();
    $app = new App($container);
    
    // Configure your app...
    $app->get('/hello', function () {
        return 'Hello World';
    });
    
    $app->run();
  9. Bootstrap a Nano application with AppFactory

    master

    Use Hyperf\Nano\Factory\AppFactory::createBase() to initialize a Nano application. The method accepts a host, a port, and an optional mapping array for Dependency Injection (DI) container bindings (e.g., [Interface::class => Implementation::class]).

    use Hyperf\Nano\Factory\AppFactory;
    
    $app = AppFactory::createBase('0.0.0.0', 9501, [
        FooInterface::class => Foo::class,
    ]);
  10. Configure Routing in Nano

    master

    The $app instance integrates all Hyperf router methods. You can define single routes or group them using $app->addGroup().

    <?php
    use Hyperf\Nano\Factory\AppFactory;
    
    require_once __DIR__ . '/vendor/autoload.php';
    
    $app = AppFactory::create();
    
    $app->addGroup('/nano', function () use ($app) {
        $app->addRoute(['GET', 'POST'], '/{id:\d+}', function($id) {
            return '/nano/'.$id;
        });
        $app->put('/{name:.+}', function($name) {
            return '/nano/'.$name;
        });
    });
    
    $app->run();
  11. Define Routes and Route Groups

    master

    $app integrates all methods from the Hyperf router. You can define individual routes (GET, POST, PUT, etc.) or group them using addGroup().

    $app->addGroup('/nano', function () use ($app) {
        $app->addRoute(['GET', 'POST'], '/{id:\d+}', function($id) {
            return '/nano/'.$id;
        });
        $app->put('/{name:.+}', function($name) {
            return '/nano/'.$name;
        });
    });