Symfony 创建路由
最后修改于 2020 年 7 月 5 日
Symfony 创建路由教程展示了如何使用注解、XML、YAML 和 PHP 在 Symfony 中创建路由。
Symfony
Symfony 是一套可重用的 PHP 组件,也是一个用于 Web 项目的 PHP 框架。Symfony 于 2005 年发布为自由软件。Symfony 的最初作者是 Fabien Potencier。Symfony 深受 Spring Framework 的启发。
路由
路由是从 URL 路径到控制器的映射。例如,/about URL 被映射到 MyController 的 about() 方法。
Symfony 允许使用注解、XML、YAML 和 PHP 创建路由。
Symfony 创建路由示例
在下面的示例中,我们用不同的方式创建路由。
$ composer create-project symfony/skeleton createroutes
使用 composer,我们创建一个新的 Symfony 骨架项目。
$ cd createroutes
我们进入项目目录。
$ composer require maker $ composer require annotations
我们安装两个模块:annotations 和 maker。
$ composer require server --dev
我们安装开发 Web 服务器。
$ php bin/console make:controller MyController
创建了一个 MyController。
src/Controller/MyController.php
<?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
class MyController extends AbstractController
{
/**
* @Route("/about", name="about")
*/
public function about()
{
return new Response("This is About page", Response::HTTP_OK,
['content-type' => 'text/plain']);
}
public function index()
{
return new Response("This is Index page", Response::HTTP_OK,
['content-type' => 'text/plain']);
}
public function news()
{
return new Response("This is News page", Response::HTTP_OK,
['content-type' => 'text/plain']);
}
public function contacts()
{
return new Response("This is Contacts page", Response::HTTP_OK,
['content-type' => 'text/plain']);
}
}
MyController 有四个路由,分别使用注解、XML、YAML 和 PHP 创建。每个路由都返回简单的文本。
/**
* @Route("/about", name="about")
*/
public function about()
{
return new Response("This is About page", Response::HTTP_OK,
['content-type' => 'text/plain']);
}
about 路由使用 @Route 注解进行映射。
config/routes.yaml
index:
path: /
controller: App\Controller\MyController::index
index 路由在 YAML 配置文件中进行映射。
config/routes.xml
<?xml version="1.0" encoding="UTF-8" ?>
<routes xmlns="https://symfony.com.cn/schema/routing"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="https://symfony.com.cn/schema/routing
https://symfony.com.cn/schema/routing/routing-1.0.xsd">
<route id="contacts" controller="App\Controller\MyController::contacts" path="/contacts" >
</route>
</routes>
contacts 路由在 XML 配置文件中进行映射。
config/routes.php
<?php
use App\Controller\MyController;
use Symfony\Component\Routing\Route;
use Symfony\Component\Routing\RouteCollection;
$routes = new RouteCollection();
$routes->add('news', new Route('/news', [
'_controller' => [MyController::class, 'news']
]));
return $routes;
news 路由是使用 PHP 代码创建的。
$ php bin/console server:run
我们启动开发服务器。
$ curl localhost:8000/about This is About page $ curl localhost:8000/news This is News page $ curl localhost:8000/ This is Index page $ curl localhost:8000/contacts This is Contacts page
我们使用 curl 生成请求。
在本教程中,我们使用注解、XML、YAML 配置和 PHP 代码在 Symfony 中创建了路由。
列出 所有 Symfony 教程。