在2019年4月25日, Slim微框架的新的主要alpha
版本出现了曙光,并在5月18日变为beta
。 我建议您熟悉新版本。
下切:
- 关于框架的创新
- 在Slim-4上编写一个简单的应用程序
- 关于Slim和PhpStorm友谊
Slim 4的新功能
与版本3相比的主要创新:
- PHP的最低版本是7.1。
- 支持PSR-15(中间件);
- 删除了执行HTTP消息。 安装任何与PSR-7兼容的库并使用;
- 删除了Pimple依赖项。 安装您喜欢的与PSR-11兼容的容器并使用它;
- 使用路由器的能力(以前,无法放弃FastRoute );
- 更改了错误处理的实现;
- 更改了响应输出的实现;
- 添加了工厂以创建应用程序的实例;
- 删除设置;
- Slim不再将
default_mimetype
设置为空字符串,因此您需要使用ini_set('default_mimetype', '')
自己在php.ini
或应用程序中安装它; - 现在,应用程序请求处理程序仅接受请求对象(在旧版本中,它接受请求和响应对象)。
现在如何创建应用程序?
在第三个版本中,创建应用程序如下所示:
<?php use Psr\Http\Message\ServerRequestInterface; use Psr\Http\Message\ResponseInterface; use Slim\App; require 'vendor/autoload.php'; $settings = [ 'addContentLengthHeader' => false, ]; $app = new App(['settings' => $settings]); $app->get('/hello/{name}', function (ServerRequestInterface $request, ResponseInterface $response, array $args) { $name = $args['name']; $response->getBody()->write("Hello, $name"); return $response; }); $app->run();
现在,应用程序构造函数接受以下参数:
现在,您还可以使用应用程序工厂\Slim\Factory\AppFactory
的静态create
方法。
此方法接受与输入相同的参数,只有它们都是可选的。
<?php use Psr\Http\Message\ServerRequestInterface; use Psr\Http\Message\ResponseInterface; use Slim\Factory\AppFactory; require 'vendor/autoload.php'; $app = AppFactory::create(); $app->get('/hello/{name}', function (ServerRequestInterface $request, ResponseInterface $response) { $name = $request->getAttribute('name'); $response->getBody()->write("Hello, $name"); return $response; }); $app->run();
给我404错误!
如果尝试打开不存在的页面,则会得到响应代码500
而不是404
。 为了正确处理错误,您需要连接\Slim\Middleware\ErrorMiddleware
<?php use Psr\Http\Message\ServerRequestInterface; use Psr\Http\Message\ResponseInterface; use Slim\Factory\AppFactory; use Slim\Middleware\ErrorMiddleware; require 'vendor/autoload.php'; $app = AppFactory::create(); $middleware = new ErrorMiddleware( $app->getCallableResolver(), $app->getResponseFactory(), false, false, false ); $app->add($middleware); $app->get('/hello/{name}', function (ServerRequestInterface $request, ResponseInterface $response) { $name = $request->getAttribute('name'); $response->getBody()->write("Hello, $name"); return $response; }); $app->run();
中间件
中间件现在应该是PSR-15的实现。 作为例外,可以传递函数,但签名必须与\Psr\Http\Server\MiddlewareInterface
接口的process()
方法匹配
<?php use Psr\Http\Message\ServerRequestInterface; use Psr\Http\Message\ResponseInterface; use Psr\Http\Server\RequestHandlerInterface; use Slim\Factory\AppFactory; require 'vendor/autoload.php'; $app = AppFactory::create(); $app->add(function (ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface { $response = $handler->handle($request); return $response->withHeader('Content-Type', 'application/json'); });
不再支持签名($request, $response, $next)
如何在没有设置的情况下生活?
您可以没有设置地生活。 提供的工具将帮助我们实现这一目标。
httpVersion
和responseChunkSize
httpVersion
负责在响应中输出协议版本。
responseChunkSize
设置确定了发送到浏览器时从响应主体读取的每个块的大小。
现在,可以将这些功能分配给答案的发出者。
写发射器
<?php
我们连接到应用程序
<?php use App\ResponseEmitter; use Slim\Factory\AppFactory; require 'vendor/autoload.php'; $app = AppFactory::create(); $serverRequestFactory = \Slim\Factory\ServerRequestCreatorFactory::create(); $request = $serverRequestFactory->createServerRequestFromGlobals();
outputBuffering
此设置允许打开/关闭输出缓冲。 设定值:
- false-关闭缓冲(对
echo
, print
语句的所有调用都将被忽略)。 'append'
所有对echo
, print
语句的调用都添加在响应正文之后'prepend'
所有对echo
, print
语句的调用都添加在响应主体之前
\Slim\Middleware\OutputBufferingMiddleware
开发人员建议将此\Slim\Middleware\OutputBufferingMiddleware
替换为该选项, \Slim\Middleware\OutputBufferingMiddleware
其构造函数\Slim\Middleware\OutputBufferingMiddleware
PSR-17兼容的流工厂和可以等于append
或prepend
的模式
<?php use Slim\Factory\AppFactory; use Slim\Factory\Psr17\SlimPsr17Factory; use Slim\Middleware\OutputBufferingMiddleware; require 'vendor/autoload.php'; $app = AppFactory::create(); $middleware = new OutputBufferingMiddleware(SlimPsr17Factory::getStreamFactory(), OutputBufferingMiddleware::APPEND); $app->add($middleware);
determineRouteBeforeAppMiddleware
此设置允许从中间件中的请求对象获取当前路由
提供了一个替代\Slim\Middleware\RoutingMiddleware
<?php use Slim\Factory\AppFactory; use Slim\Middleware\RoutingMiddleware; require 'vendor/autoload.php'; $app = AppFactory::create(); $middleware = new RoutingMiddleware($app->getRouteResolver()); $app->add($middleware);
displayErrorDetails
该设置允许显示错误详细信息。 调试时,使工作变得更轻松。
还记得\Slim\Middleware\ErrorMiddleware
吗? 在这里它将帮助我们!
<?php use Slim\Factory\AppFactory; use Slim\Middleware\ErrorMiddleware; require 'vendor/autoload.php'; $app = AppFactory::create(); $middleware = new ErrorMiddleware( $app->getCallableResolver(), $app->getResponseFactory(), true,
addContentLengthHeader
此设置允许启用/禁用Content-Length
标头与响应正文中数据量的值的自动添加
替换中间件选项\Slim\Middleware\ContentLengthMiddleware
<?php use Slim\Factory\AppFactory; use Slim\Middleware\ContentLengthMiddleware; require 'vendor/autoload.php'; $app = AppFactory::create(); $middleware = new ContentLengthMiddleware(); $app->add($middleware);
routerCacheFile
现在您可以直接安装路由器缓存文件
<?php use Slim\Factory\AppFactory; require 'vendor/autoload.php'; $app = AppFactory::create(); $app->getRouteCollector()->setCacheFile('/path/to/cache/router.php');
在Slim-4上创建应用程序
为了进一步了解该框架,我们将编写一个小应用程序。
该应用程序将具有以下路由:
/hello/{name}
-欢迎页面;/
-重定向到页面/hello/world
- 其他路线将返回带有404错误的自定义页面。
逻辑将在控制器中,我们将通过Twig模板引擎渲染页面
另外,添加一个基于Symfony Console组件的控制台应用程序,并使用显示路由列表的命令
步骤0。安装依赖项
我们将需要:
我选择超轻型/容器作为依赖项容器 ,因为它轻巧,简洁并且符合标准。
PSR-7和PSR-17 Slim开发人员在一个软件包中提供了slim / psr7 。 我们将使用它
假定已经安装了Composer软件包管理器。
我们为项目创建一个文件夹(将使用/path/to/project
作为示例)并转到该文件夹。
将composer.json
文件添加到具有以下内容的项目中:
{ "require": { "php": ">=7.1", "slim/slim": "4.0.0-beta", "slim/psr7": "~0.3", "ultra-lite/container": "^6.2", "symfony/console": "^4.2", "twig/twig": "^2.10" }, "autoload": { "psr-4": { "App\\": "app" } } }
并执行命令
composer install
现在,我们有了所有必需的软件包,并配置了类自动加载器。
如果我们使用git ,请添加.gitignore
文件并在其中添加vendor
目录(如果需要,还可以添加IDE的目录)
/.idea/* /vendor/*
我正在使用PhpStorm IDE 为它感到骄傲 。 为了进行舒适的开发,是时候使用容器和IDE了。
在项目的根目录中,创建.phpstorm.meta.php
文件,并在其中写入以下代码:
<?php
此代码将告诉IDE,对于实现\Psr\Container\ContainerInterface
接口的对象, get()
方法将返回其名称在参数中传递的类对象或接口实现。
步骤1.应用程序框架
添加目录:
app
应用程序代码。 我们将为类自动加载器连接名称空间;bin
控制台实用程序的目录;config
这是应用程序配置文件;- public-在Web上打开的目录(应用程序入口点,样式,js,图片等);
template
目录;var
是各种文件的目录。 日志,缓存,本地存储等
和文件:
config/app.ini
主应用程序配置;config/app.local.ini
用于local
环境的配置;app/Support/CommandMap.php
控制台应用程序命令的映射,用于延迟加载。app/Support/Config.php
配置类(以便IDE知道我们拥有哪些配置)。app/Support/NotFoundHandler.php
-404错误处理程序类。app/Support/ServiceProviderInterface.php
服务提供者的界面。app/Provider/AppProvider.php
的主要提供程序。bootstrap.php
容器组装;bin/console
控制台应用程序的入口点;public/index.php
-Web应用程序的入口点。
config / app.ini ; slim.debug=Off ; templates.dir=template ; templates.cache=var/cache/template
config / app.local.ini ; . ; slim.debug=On ; templates.cache=
哦,是的,从存储库中排除环境配置仍然很好。 毕竟,可能会有外观/密码。 缓存也被排除。
.gitignore /.idea/* /config/* /vendor/* /var/cache/* !/config/app.ini !/var/cache/.gitkeep
应用程序/支持/ NotFoundHandler.php 现在,您可以教会PhpStorm了解哪些键具有键,以及它们的类型。
应用程序/支持/ ServiceProviderInterface.php app / Provider / AppProvider.php 我们将路由移到了容器上,这样我们就可以使用它而无需初始化\Slim\App
对象。
建议授予该文件执行权限
chmod +x ./bin/console
验证码
启动控制台应用程序:
./bin/console
作为响应, symfony/console
组件的欢迎窗口应该出现,并带有两个可用命令help
和list
。
Console Tool Usage: command [options] [arguments] Options: -h, --help Display this help message -q, --quiet Do not output any message -V, --version Display this application version --ansi Force ANSI output --no-ansi Disable ANSI output -n, --no-interaction Do not ask any interactive question -v|vv|vvv, --verbose Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug Available commands: help Displays help for a command list Lists commands
现在启动Web服务器。
php -S localhost:8080 -t public public/index.php
并在localhost上打开任何URL:8080。
所有请求都应返回带有代码404
和空主体的响应。
发生这种情况是因为我们没有列出路线。
我们仍然需要连接渲染,编写模板,控制器和设置路线。
步骤2.渲染
添加模板template/layout.twig
。 这是所有页面的基本模板。
模板/ layout.twig {# template/layout.twig #} <!DOCTYPE html> <html lang="en"> <head> <title>{% block title %}Slim demo{% endblock %}</title> </head> <body> {% block content %}{% endblock %} </body> </html>
添加欢迎页面template/hello.twig
模板/ hello.twig {# template/hello.twig #} {% extends 'layout.twig' %} {% block title %}Slim demo::hello, {{ name }}{% endblock %} {% block content %} <h1>Welcome!</h1> <p>Hello, {{ name }}!</p> {% endblock %}
和错误页面template/err404.twig
模板/ err404.twig {# template/err404.twig #} {% extends 'layout.twig' %} {% block title %}Slim demo::not found{% endblock %} {% block content %} <h1>Error!</h1> <p>Page not found =(</p> {% endblock %}
添加渲染提供app/Provider/RenderProvider.php
应用程序/提供程序/ RenderProvider.php 在引导程序中打开提供程序
将渲染添加到404错误处理程序
应用程序/支持/ NotFoundHandler.php(DIFF) 应用程序/提供程序/ AppProvider.php(DIFF) 404 .
3.
2:
app/Controller/HomeController.php
—app/Controller/HelloController.php
—
( URL ), — ( html)
app/Controller/HomeController.php app/Controller/HelloController.php ,
app/Provider/WebProvider.php - ( )...
php -S localhost:8080 -t public public/index.php
… http://localhost:8080 , http://localhost:8080/hello/world
world'.
http://localhost:8080/hello/ivan ivan'.
, , http://localhost:8080/helo/world 404 .
4.
route:list
app/Command/RouteListCommand.php ,
app/Provider/CommandProvider.php ...
./bin/console route:list
… :
Routes ====== --------------- --------- ------- ------------------------------------- Route Methods Name Handler --------------- --------- ------- ------------------------------------- / GET index App\Controller\HomeController:index /hello/{name} GET hello App\Controller\HelloController:show --------------- --------- ------- -------------------------------------
, , !
, Slim — routes.php
( ), . — , , .