composer 包 slim使用案例,一个简单的路由解决方案

nginx配置文件修改

location / {
        try_files $uri /index.php$is_args$args;
    }

设置好nginx伪静态,把所有的请求方式都转向到index.php文件

然后在目录里建index.php文件

在目录里安装如下三个composer包

composer require slim/slim guzzlehttp/psr7 http-interop/http-factory-guzzle

然后打开index.php文件,修改内容为如下:

<?php

use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Slim\Factory\AppFactory;

require "vendor/autoload.php";

$app = AppFactory::create();

// Define app routes
$app->get('/hello/{name}', function (Request $request, Response $response, $args) {
    $name = $args['name'];
    $response->getBody()->write("Hello, $name");
    return $response;
});
$app->get('/welcome/{name}', function (Request $request, Response $response, $args) {
    $name = $args['name'];
    $response->getBody()->write("welcome, $name");
    return $response;
});
$app->get('/json',function (Request $request, Response $response){
    $query = $request->getQueryParams();

    $data = array('name' => $query['name'] ?? 'null', 'age' => 40);
    $payload = json_encode($data);

    $response->getBody()->write($payload);
    return $response
        ->withHeader('Content-Type', 'application/json');
});
$app->get('/form',function (Request $request, Response $response){
    $html = <<<EOT
<html>
<head>form demo
</head>
<body>
    <form action="/action" method="post" enctype="multipart/form-data">
        <input type="text" name="name" value="tu6ge" />
        <input type="text" name="language" value="php" />
        <input type="file" name="avatar" />
        <button type="submit" >submit</button>
    </form>
</body>
</html>
EOT;
    $response->getBody()->write($html);
    return $response;
});
$app->post('/action',function (Request $request, Response $response){
    $info = $request->getParsedBody();
    print_r($info);
    $files = $request->getUploadedFiles();
    foreach ($files as $file){
        $file->moveTo('./upload/'.date('H-i-s').'.txt');
    }
    $response->getBody()->write('file save success');
    return $response;
});

// Run app
$app->run();

输入对应的路由,比如/hello/tu6ge即可访问对应的内容

转载于:https://www.cnblogs.com/tu6ge/p/11373347.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值