brandembassy/slim-nette-extension

5.10 2024-04-30 09:59 UTC

README

CircleCI Total Downloads Latest Stable Version

用于API集成的SLIM扩展

此扩展将Slim的强大功能引入使用Nette DI的应用程序中。它使您能够轻松地使用Slim中间件堆栈并轻松地开发您的API。

该一般思想已在这篇文章中讨论。(捷克语)

哲学

单一职责

主要思想是将处理请求的代码的责任委托给独立的中间件。例如

  • 身份验证
  • 验证
  • 业务逻辑

Slim中中间件的工作原理在此处描述这里

易于配置

借助Nette DI及其neon配置语法,该包提供了一种强大而简单的方式来定义您的API。

用法

让我们开始吧!

composer require brandembassy/slim-nette-extension

扩展

现在通过将此代码添加到您的config.neon中注册新扩展

extensions:
    slimApi: BrandEmbassy\Slim\DI\SlimApiExtension # Register extension

slimApi: # Configure it
    slimConfiguration:
        settings:
            removeDefaultHandlers: true # It's recommended to disable original error handling 
                                        # and use your own error handlers suited for needs of your app. 

    apiDefinitionKey: api # Your API definition will be under this key in "parameters" section. 

第一个API端点

现在让我们假设您想创建一个创建频道的REST端点,[POST] /new-api/2.0/channels

您需要在config.neon中的parameters.api部分中定义。

服务和中间件都必须是DI容器中注册的服务。

parameters:
    api:
        handlers:
            notFound: App\NotFoundHandler # Called when not route isn't matched by URL
            notAllowed: App\NotAllowedHandler # Called when route isn't matched by method
            error: App\ApiErrorHandler # Called when unhandled exception bubbles out

        routes:
            new-api: # This is name of your API
                "2.0": # Version of your API
                    '/channels': # Matched URL will be "your-domain.org/new-api/2.0/channels"
                        post:
                            # This is service will be invoked to handle the request
                            service: App\CreateChannelAction
                            
                            # Here middleware stack is defined. It's evaluated from bottom to top. 
                            middleware:
                                - App\SomeOtherMiddleware # last in row
                                - App\UsuallyRequestDataValidationMiddleware # second in row
                                - App\SomeAuthMiddleware # this one is called first 

        beforeRouteMiddlewares:
            # this is called for each route, before route middlewares
            - App\SomeBeforeRequestMiddleware 
            
        beforeRequestMiddlewares:
            # this is called for each request, even when route does NOT exist (404 requests)
            - App\SomeBeforeRouteMiddleware tests/Dummy/BeforeRequestMiddleware.php

您也可以通过其名称引用命名服务。

有关更多示例,请参阅tests/SlimApplicationFactoryTest.phptests/config.neon

执行

现在您可以从您的DI容器中简单获取SlimApplicationFactory类(或更好自动注入),创建应用并运行它。

$factory = $container->getByType(SlimApplicationFactory::class);
$factory->create()->run();