版本要求

Slim 3要求PHP 5.5+

新的路由函数使用说明

$app->get('/', function (Request $req,  Response $res, $args = []) {

		return $res->withStatus(400)->write('Bad Request');
		
});

获取GET,POST变量

//args 获取的是路由参数
$app->get('/', function (Request $req,  Response $res, $args = []) {
  $myvar1 = $req->getParam('myvar'); //获取所有的_GET,_POST值 ,不兼容PSR-7
  $myvar2 = $req->getParsedBody()['myvar']; //获取_POST  [兼容PSR-7]
  $myvar3 = $req->getQueryParams()['myvar']; //获取 _GET [兼容PSR-7]
});

$app->get('/test/{name}', function (Request $req,  Response $res, $args = []) {
  retrun $res->write($args['name']); //访问http://z.slim.com/test/vilay  输出: vilay
});

勾子(Hooks)

Slim 3没有勾子的概念了。因为勾子功能已经在中间件中实现,所以移除了。你可以非常容易的在中间件中实现勾子的代码。

去除HTTP 缓存

Slim 3中去处了http缓存,功能置于它内置的模块中 Slim\Http\Cache

去除 Stop/Halt

Slim 3的核心中移除了 Stop/Halt 。在应用中,你可以通过使用 withStatus()withBody() 来实现功能。

修改重定向(Redirect)

Slim v2.x 中通过使用帮助函数 $app->redirect() 来触发重定向请求,在 Slim v3.x 中我们通过 Response 类来实现同样的功能。

示例:

$app->get('/', function ($req, $res, $args) {
	return $res->withStatus(301)->withHeader("Location", "yournewuri");
});

中间件

使用说明—中间件从原来通过类实现过渡到使用函数来实现。

新的使用方式:

use Psr\Http\Message\RequestInterface as Request;
use Psr\Http\Message\ResponseInterface as Response;

$app->add(function (Request $req,  Response $res, callable $next) {
		//进入路由之前代码实现
		$newRespose = $next($req, $res);
		//路由之后到代码实现
		return $newResponse; //继续
});

当然,你也可以继续使用类的方式实现:

namespace My;

use Psr\Http\Message\RequestInterface as Request;
use Psr\Http\Message\ResponseInterface as Response;

class Middleware
{
		function __invoke(Request $req,  Response $res, callable $next) {
				//代码实现
				$newRespose = $next($req, $res);
				//代码实现
				return $newResponse; 
		}
}


// 注册中间件
$app->add(new My\Middleware());
// 或者
$app->add(My\Middleware::class);

中间件的执行

应用的中间件执行顺序为最后进入的最先执行(即LIFE:Last In First Executed)。

Flash消息

Flash消息不再作为Slim v3的核心部分,但是分离出来在 Slim Flash 包中

Cookies

Slim v3中cookies从核心中移除,通过 FIG Cookies 实现,兼容PSR-7 cookie组件

移除Crypto

在Slim v3 中从核心中移除了crypto

新的路由

Slim v3 使用 FastRoute 一个更新,更强大的路由组件.

路由中间件

Slim v3 添加路由中间件的语法

$app->get(…)->add($mw2)->add($mw1);

在路由中用 pathFor()替代urlFor()

urlFor()函数重命名为pathFor(),可以在 router 对象中看到

$app->get('/', function ($request, $response, $args) {
$url = $this->router->pathFor('home');
$response->write("<a href='$url'>Home</a>");
return $response;
})->setName('home');

注入和容器 …构建

Slim v3使用 Pimple 做为依赖注入容器.

//index.php
$app = new Slim\App(
		new \Slim\Container(
				include "../config/container.config.php"
		)
);

//Slim will grab the Home class from the container defined below and execute its index method
//If the class is not defined in the container Slim will still contruct it and pass the container as the first arugment to the constructor!
$app->get('/', Home::class . ':index');


//In container.config.php
// We are using the SlimTwig here
return [
		"settings" => [
				'viewTemplatesDirectory' => "../templates",
		],
		'twig' => [
				'title' => '',
				'description' => '',
				'author' => ''
		],
		'view' => function ($c) {
				$view = new Twig(
						$c['settings']['viewTemplatesDirectory'],
						[
								'cache' => false //"../cache"
						]
				);

				// Instantiate and add Slim specific extension
				$view->addExtension(
						new TwigExtension(
								$c['router'],
								$c['request']->getUri()
						)
				);

				foreach ($c['twig'] as $name => $value) {
						$view->getEnvironment()->addGlobal($name, $value);
				}

				return $view;
		},
		Home::class => function ($c) {
				return new Home($c['view']);
		}
];

PSR-7 对象

Request, Response, Uri & UploadFile 是不可改变的.

这句话的意思是如果你改变了这个对象,之前的实例并不会更新.

// THIS IS WRONG. The change will not pass through.
$app->add(function (Request $request, Response $response, $next) {
    $request->withAttribute("abc", "def");
    return $next($request, $response);
});

//This is Correct
$app->add(function (Request $request, Response $response, $next) {
    $request = $request->withAttribute("abc", "def");
    return $next($request, $response);
});

消息主体以流形式传输

// ...
$image = __DIR__ . ‘/huge_photo.jpg';
$body = new Stream($image);
$response = (new Response())
		 ->withStatus(200, 'OK')
		 ->withHeader('Content-Type', 'image/jpeg')
		 ->withHeader(‘Content-Length', filesize($image))
		 ->withBody($body);
// ...

文本输出:

// ...
$response = (new Response())->getBody()->write("Hello world!")

// Or Slim specific: Not PSR-7 compliant
$response = (new Response())->write("Hello world!");
// ...

文档翻译的并不是很专业,仅供个人学习作用,建议看官方文档。

如有兴趣,请看下一篇 SLIM 3 文档(三)-WEB 服务器配置