bnf/slim-interop-service-provider

Slim 兼容的 container-interop/service-provider 服务提供者

4.2.0 2019-08-14 08:04 UTC

This package is auto-updated.

Last update: 2024-09-14 20:09:44 UTC


README

为 Slim 提供 container-interop/service-provider 支持。

安装

$ composer require bnf/slim-interop-service-provider:^4.0

用法

Bnf\SlimInterop\ServiceProvider 添加到服务提供者列表中,以注册默认的 Slim 服务。

将其指定为 第一个 服务提供者,以便能够覆盖或扩展默认服务。

new Container([
    new \Bnf\SlimInterop\ServiceProvider,
    new YouServiceProvider,
]);

示例

使用兼容 container-interop/service-provider 的容器 bnf/di 的示例用法。

$ composer require bnf/slim-interop-service-provider:^4.0 bnf/di:~0.1.0 slim/slim:^4.0 slim/psr7:~0.4.0
<?php
declare(strict_types = 1);
require 'vendor/autoload.php';

use Bnf\Di\Container;
use Bnf\SlimInterop\ServiceProvider as SlimServiceProvider;
use Psr\Container\ContainerInterface;
use Interop\Container\ServiceProviderInterface;
use Slim\App;

class Index
{
    public function __invoke($request, $response) {
        $response->getBody()->write('Hello World.');
        return $response;
    }
}

$container = new Container([
    // Register default slim services
    new SlimServiceProvider,

    // Register own services and configuration
    new class implements ServiceProviderInterface {
        public function getFactories(): array
        {
            return [
                'slim.display_error_details' => function(): bool {
                    return true;
                },
                Index::class => function (ContainerInterface $container): Index {
                    return new Index;
                }
            ];
        }
        public function getExtensions(): array
        {
            return [
                // configure app route and middlewares as extension to the App class
                App::class => function (ContainerInterface $container, App $app): App {
                    $app->add(\Slim\Middleware\ErrorMiddleware::class);

                    $app->get('/', Index::class);

                    return $app;
                },
            ];
        }
    }
]);

$app = $container->get(App::class);
$app->run();