這個教程是基於symfony5進行編寫,以後再出高版本的symfony,那麼就可以只出一套針對這個高版本的特性進行編寫,該系列教程會一直延續更新。
點贊再看,養成習慣,微信搜索公衆號【程序員老班長】關注這個互聯網老班長,查看更多系列文章
目錄
基於上一節裏面的my_project_website-skeleton項目,繼續。
我們現在開始創建控制器和前端頁面。
1,新建控制器
在 src/Controller裏面創建 HelloController,代碼如下:
<?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
class HelloController extends AbstractController
{
public function index(){
$number = random_int(0, 100);
return new Response(
'<html><body>Hello number: '.$number.'</body></html>'
);
}
}
2,添加路由
config/routes.yaml裏面添加:
app_hello: path: /hello/index controller: App\Controller\HelloController::index
php -S 127.0.0.1:8000 -t public
打開瀏覽器:
http://127.0.0.1:8000/hello/index
出現界面:
可以看到這個我們寫的Controller已經開始工作。
3,爲控制器添加新方法
我們給這個Controller再添加一個方法:
public function index1(){
$number = random_int(0, 100);
return $this->render('hello/number.html.twig', [
'number' => $number,
]);
}
4,新建模板文件
再在templates/hello下新建文件:number.html.twig,
<h1>Your lucky number is {{ number }}</h1>
5,添加路由
在config/routes.yaml裏面添加:
app_hello1:
path: /hello/index1
controller: App\Controller\HelloController::index1
我們在瀏覽器裏面訪問:
http://127.0.0.1:8000/hello/index1
可以看到:
裏面的數字是隨機數字,每次訪問看到的數字都不一樣,所以當你這樣運行的時候看到數字會和我的不一樣。
在控制器裏面返回的對象不能爲NULL,必須返回一個Response對象。
6,Twig模板
可以看到我們之前創建的前端頁面文件後綴爲html.twig,這實際上就一個twig文件,關於twig,它是一個模板引擎,我們來看下的介紹:
Twig是一款靈活、快速、安全的PHP模板引擎。
它的官方網站地址:https://twig.symfony.com
關於twig的內容,後面更新的文章會詳細介紹。
7, 總結
本節主要是理解控制器和前端頁面的關係,以及如何創建控制器和前端頁面。這樣大體就對控制器、頁面、路由有了瞭解。
文章持續更新,可以微信搜索公衆號「 程序員老班長 」查看更多文章。