Slim 微型框架

最后更新于:2022-04-02 02:20:08

[TOC] ## 安装 php7+ `composer require slim/slim` php5+ `composer require slim/slim "^3.12" ` ## 快速开始 > [快速开始](http://www.slimframework.com/docs/v3/tutorial/first-app.html) ``` require_once 'vendor/autoload.php'; use \Psr\Http\Message\ServerRequestInterface as Request; use \Psr\Http\Message\ResponseInterface as Response; //创建 db $config['displayErrorDetails'] = true; $config['addContentLengthHeader'] = false; $config['db']['host'] = 'localhost'; $config['db']['user'] = 'user'; $config['db']['pass'] = 'password'; $config['db']['dbname'] = 'exampleapp'; $app = new \Slim\App(['settings' => $config]); /*创建一个容器*/ $container = $app->getContainer(); /* 添加日志数据库 */ $container['logger'] = function($c) { $logger = new \Monolog\Logger('my_logger'); $file_handler = new \Monolog\Handler\StreamHandler('../logs/app.log'); $logger->pushHandler($file_handler); return $logger; }; $this->logger->addInfo('Something interesting happened'); /* 添加 mysql 数据库 */ $container['db'] = function ($c) { $db = $c['settings']['db']; $pdo = new PDO('mysql:host=' . $db['host'] . ';dbname=' . $db['dbname'], $db['user'], $db['pass']); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC); return $pdo; }; $app->get('/hello/{name}', function (Request $request, Response $response, array $args) { $name = $args['name']; $response->getBody()->write("Hello, $name"); return $response; }); $app->run(); ``` 配置 `composer.json`,使其自动加载自定义的类 ``` { "require": { "slim/slim": "^3.1", "slim/php-view": "^2.0", "monolog/monolog": "^1.17", "robmorgan/phinx": "^0.5.1" }, "autoload": { "psr-4": { "Example\\": "classes/" } } } ``` 运行 `php -S localhost:8080 ` ### 设置中间件 > [设置中间件](https://www.slimframework.com/docs/v3/concepts/middleware.html)
';