使用symfony构建restful应用 - 项目初始化

目标:

使用 symfony 构建一个 api 基础接口

新建一个 symfony 应用

下载 symfony:

1
composer create-project symfony/skeleton my_project_name

然后把你配置的域名指向项目的public下面就可以用域名访问了。

如果你是 apache 环境记得重写 url

如果你看了官方文档:set_up的话,你可能会运行:

1
symfony server:start

或者是

1
php bin/console server:run

但是你会发现报错

1
2
[InvalidArgumentException]
There are no commands defined in the "server" namespace

这是因为没有WebServerBundle的缘故,安装:

1
composer require --dev symfony/web-server-bundle

然后用浏览器打开127.0.0.1:8000就可以看见默认页面了。

创建第一个路由

symfony配置路由的方式比较灵活。这里主要介绍两种简单的方式。

在路由配置中配置路由

在config/routes.yaml 添加一下配置(_假设你的控制器src/controll/Word_):

1
2
3
index:
path: /hello/word
controller: App\Controller\Word::index

控制器:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<?php
// src/controll/Word
namespace App\Controller;

use Symfony\Component\HttpFoundation\Response;

class Word
{
public function index()
{
$number = random_int(0, 100);

return new Response(
'<html><body>Hello word: '.$number.'</body></html>'
);
}
}

在路由hello\word下面就可以看到你的返回页面了。

使用注解路由

这种方式比较灵活,也是我个人比较推荐的路由注册方式,它直接作用于控制器的注解之中。
当然,它额外的需要你有annotations组件。安装:

1
composer require annotations

使用注解路由,我们可以把控制器改写成这样:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<?php
// src/controll/Word
namespace App\Controller;

use Symfony\Component\HttpFoundation\Response;
+ use Symfony\Component\Routing\Annotation\Route;

+ /**
+ * @Route("/hello")
+ */
class Word
{
+ /**
+ * @Route("/word",methods={"GET"})
+ */
public function index()
{
$number = random_int(0, 100);

return new Response(
'<html><body>Hello word: '.$number.'</body></html>'
);
}
}

与此同时我们可以把刚才在config/routes.yaml添加的路由hello\word删除掉了。
其中methods参数标识这个接口的请求方式,甚至可以指定多个请求方式如:

1
2
3
/**
* @Route("/word",methods={"GET","HEAD"})
*/

查看路由

输入以下命令即可查看已经注册的路由:

1
php bin/console debug:router

更多信息请查看The Routing Component

enjoy and happy coding!