php框架slim使用(2)- 路由中使用控制器类

常规路由写法:

$app->get('/hello/{name}', function (Request $request, Response $response) {
$name = $request->getAttribute('name');
$response->getBody()->write("Hello, $name");

return $response;
});


假设项目名称和文件夹叫t3

但是我们通常会把程序逻辑写在控制器类中。
首先,修改composer.json
让我们有个放自己程序的类文件的地方。


"autoload-dev": {
"psr-4": {
"Tests\\": "tests/",
"app\\": "src/app/"
}
}


然后在cmd下,
cd t3
composer install

然后
建立目录,src已存在,建立src\app\control
然后在src\app\control下建立Test.php

<?php

namespace app\control;
// use \Psr\Http\Message\ServerRequestInterface as Request;
// use \Psr\Http\Message\ResponseInterface as Response;
class Test {

public function a1( $req, $res, $args) {
// 获取 root URI
echo '$uri = $req->getUri()';
echo "<br>";
echo $req->getUri();
echo "<hr>";

$uri = $req->getUri();

echo '$uri->getScheme()';
echo "<br>";
echo $uri->getScheme();
echo "<br>";

echo '$uri->getAuthority()';
echo "<br>";
echo $uri->getAuthority();
echo "<br>";

echo '$uri->getUserInfo()';
echo "<br>";
echo $uri->getUserInfo();
echo "<br>";

echo '$uri->getHost()';
echo "<br>";
echo $uri->getHost();
echo "<br>";

echo '$uri->getPort()';
echo "<br>";
echo $uri->getPort();
echo "<br>";

echo '$uri->getPath()';
echo "<br>";
echo $uri->getPath();
echo "<br>";

echo '$uri->getBasePath()';
echo "<br>";
echo $uri->getBasePath();
echo "<br>";

echo '$uri->getQuery()';
echo "<br>";
echo $uri->getQuery();
echo "<br>";

echo '$uri->getFragment()';
echo "<br>";
echo $uri->getFragment();
echo "<br>";

echo '$uri->getBaseUrl()';
echo "<br>";
echo $uri->getBaseUrl();
echo "<br>";

return $res;
}
}


修改 src/routs.php

<?php
$app->get('/home/s', '\app\control\Test:a1' );


然后,打开浏览器
http://www.t3.com/home/s
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值