PHP框架详解 - symfony框架

2024-02-05 12:04
文章标签 详解 php 框架 symfony

本文主要是介绍PHP框架详解 - symfony框架,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

        首先说一下为什么要写symfony框架,这个框架也属于PHP的一个框架,小编接触也是3年前,原因是小编接触Golang,发现symfony框架有PHP框架的东西也有Golang的东西,所以决定总结一下,有需要的同学可以参看小编的Golang相关博客,看完之后在学习symfony效果更佳

symfony安装

3版本安转:

composer create-project symfony/framework-standard-edition symfonyphp bin/console server:run

4版本安装:

composer create-project symfony/skeleton symfonycomposer require --dev symfony/web-server-bundlephp bin/console server:start

控制器:

创建地址:symfony\src\AppBundle\Controller\TestController.php

<?phpnamespace AppBundle\Controller;//命名空间use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;//路由文件
use Symfony\Bundle\FrameworkBundle\Controller\Controller;//基础控制器//基础类
class TestController extends Controller
{/*** 一定要写,定义路由(page表示参数,requirements表示数据验证)* @Route("/test/index/{page}", requirements = {"page": "\d+"})*/public function indexAction($page="") {echo "Hellow word"."<br />";echo "获取参数:".$page;die;}
}

路由参数:

单参数

访问地址:http://127.0.0.1:8000/test/index/1

访问地址:http://127.0.0.1:8000/test/index/2

​​

多参数:

public function indexAction($page="",$limit="") {echo "Hellow word"."<br />";echo "获取参数1:".$page."<br />";echo "获取参数2:".$limit;die;
}

访问地址:http://127.0.0.1:8000/test/index/1&10

​​

重定向:

访问地址:http://127.0.0.1:8000/test/jump

/*** @Route("/test/jump")*/
public function jump(){echo "当前方法是:jump";return $this->redirect("/test/index/2&10");die;
}

模板引擎:

Twig语法:

{{...}} - 将变量或表达式的结果打印到模板。

{%...%} - 控制模板逻辑的标签。 它主要用于执行功能。

{#...#} - 评论语法。 它用于添加单行或多行注释。

控制器:

/*** @Route("/test/template_en")*/
public function template_en(){return $this->render("default/test.html.twig",['controller_name' => "Test",'func_name' => "template_en",]);
}

页面:

{% extends 'base.html.twig' %}{% block body %}<div id="wrapper"><div id="container"><h1>WELCOM TO TEST</h1><div>控制器:{{controller_name}}</div><div>方法名:{{func_name}}</div></div></div>
{% endblock %}{% block stylesheets %}
<style>body { background: #F5F5F5; font: 18px/1.5 sans-serif; }h1, h2 { line-height: 1.2; margin: 0 0 .5em; }h1 { font-size: 36px; }h2 { font-size: 21px; margin-bottom: 1em; }p { margin: 0 0 1em 0; }a { color: #0000F0; }a:hover { text-decoration: none; }code { background: #F5F5F5; max-width: 100px; padding: 2px 6px; word-wrap: break-word; }#wrapper { background: #FFF; margin: 1em auto; max-width: 800px; width: 95%; }#container { padding: 2em; }#welcome h1 span { display: block; font-size: 75%; }
</style>
{% endblock %}

项目配置:

通过.yml文件实现配置文件自定义(Golang使用.yaml定义,实际上两者是一个东西)

一个Symfony项目有三种环境(dev、test和prod)

 

环境切换:AppKernel类负责加载你指定的配置文件(修改配置实现环境的切换)

基础方法:

切换目标文件:

表单:

        传统意义上表单是通过构建一个表单对象并将其渲染到模版来完成的。现在,在控制器里即可完成所有这些,这个是啥意思?简单点来说就是:使用PHP创建表单,而不是使用H5表单,具体代码如下:

类:

地址:symfony\src\AppBundle\Entity\Task.php
<?php
namespace AppBundle\Entity;class Task
{private $studentName;private $studentId;public $password;private $address;public $joined;public $gender;private $email;private $marks;public $sports;public function getUserName() {return $this->studentName;}public function setUserName($studentName) {$this->studentName = $studentName;}public function getUserId() {return $this->studentId;}public function setUserId($studentid) {$this->studentid = $studentid;}public function getAddress() {return $this->address;}public function setAddress($address) {$this->address = $address;}public function getEmail() {return $this->email;}public function setEmail($email) {$this->email = $email;}public function getMarks() {return $this->marks;}public function setMarks($marks) {$this->marks = $marks;}
}
?>

控制器:

地址:symfony\src\AppBundle\Controller\TestController.php
<?phpnamespace AppBundle\Controller;//命名空间use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\PasswordType;
use Symfony\Component\Form\Extension\Core\Type\EmailType;
use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
use Symfony\Component\Form\Extension\Core\Type\PercentType;
use Symfony\Component\Form\Extension\Core\Type\RepeatedType;
use Symfony\Component\HttpFoundation\Request;//基础类
class TestController extends Controller
{/*** @Route("/test/form_test")*/public function form_test(Request $request){//初始化对象$task = new Task();//创建$form = $this->createFormBuilder($task)->add('UserName', TextType::class,array('label'=>'姓名'))->add('UserId', TextType::class,array('label'=>'ID'))->add('password', RepeatedType::class, array('type'=>PasswordType::class,'invalid_message'=>'请填写密码','options'=>array('attr'=>array('class'=>'password-field')),'required'=>true,'first_options'=> array('label'=>'密码'),'second_options'=>array('label'=>'确认密码'),))->add('address', TextareaType::class,array('label'=>'地址'))->add('joined', DateType::class, array('widget'=>'choice','label'=>'生日'))->add('gender', ChoiceType::class,array('choices'=> array('男'=>true,'女'=>false,),'label'=>'性别'))->add('email', EmailType::class,array("label"=>"邮箱"))->add('marks', PercentType::class,array("label"=>"百分比"))->add('sports', CheckboxType::class, array('label'=>'是否班干部','required'=>false,))->add('save', SubmitType::class, array('label'=>'提交'))->getForm();$form->handleRequest($request);if ($form->isSubmitted() && $form->isValid()) {$task = $form->getData();echo "获取数据:<br />";var_dump($task);die;}//渲染return $this->render('default/form_test.html.twig', array('form' => $form->createView(),));}
}

页面:

地址:symfony\app\Resources\views\default\form_test.html.twig

{% extends 'base.html.twig' %}{% block body %}<h3>表单示例</h3><div id="simpleform">{{ form_start(form) }}{{ form_widget(form) }}{{ form_end(form) }}</div>
{% endblock %}{% block stylesheets %}<style>h3{text-align: center;}#simpleform {width:50%;border:2px solid grey;padding:14px;margin-left: 25%;}#simpleform label {font-size:14px;float:left;width:300px;text-align:right;display:block;}#simpleform span {font-size:11px;color:grey;width:100px;text-align:right;display:block;}#simpleform input {border:1px solid grey;font-family:verdana;font-size:14px;color:light blue;height:24px;margin: 0 0 10px 10px;}#simpleform textarea {border:1px solid grey;font-family:verdana;font-size:14px;color:light blue;height:120px;width:250px;margin: 0 0 20px 10px;}#simpleform select {margin: 0 0 20px 10px;}#simpleform button {clear:both;margin-left:30%;background: grey;color:#FFFFFF;border:solid 1px #666666;font-size:16px;width: 20rem;}</style>
{% endblock %}

打印数据:

object(AppBundle\Entity\Task)#2714 (10) 
{["studentName":"AppBundle\Entity\Task":private]=> string(1) "1" ["studentId":"AppBundle\Entity\Task":private]=> NULL ["password"]=> string(7) "3456789" ["address":"AppBundle\Entity\Task":private]=> string(1) "4" ["joined"]=> object(DateTime)#5649 (3) { ["date"]=> string(26) "2019-01-01 00:00:00.000000" ["timezone_type"]=> int(3)["timezone"]=> string(3) "UTC" } ["gender"]=> bool(true) ["email":"AppBundle\Entity\Task":private]=> string(8) "6@qq.com" ["marks":"AppBundle\Entity\Task":private]=> float(0.07) ["sports"]=> bool(true) ["studentid"]=> string(1) "2" }

文件上传:

修改配置文件:

打开扩展:php.ini    extension=php_fileinfo.dll
修改配置文件:symfony\app\config\config.yml

类:

<?php
namespace AppBundle\Entity;class Task
{public $photo;public function getPhoto() {return $this->photo;}public function setPhoto($photo) {$this->photo = $photo;return $this;}
}
?>

控制器:

<?phpnamespace AppBundle\Controller;//命名空间//基础类
class TestController extends Controller
{/*** @Route("/test/form_test")*/public function form_test(Request $request){//初始化对象$task = new Task();//创建$form = $this->createFormBuilder($task)->add('UserName', TextType::class,array('label'=>'姓名'))->add('UserId', TextType::class,array('label'=>'ID'))->add('password', RepeatedType::class, array('type'=>PasswordType::class,'invalid_message'=>'请填写密码','options'=>array('attr'=>array('class'=>'password-field')),'required'=>true,'first_options'=> array('label'=>'密码'),'second_options'=>array('label'=>'确认密码'),))->add('address', TextareaType::class,array('label'=>'地址'))->add('joined', DateType::class, array('widget'=>'choice','label'=>'生日'))->add('gender', ChoiceType::class,array('choices'=> array('男'=>true,'女'=>false,),'label'=>'性别'))->add('email', EmailType::class,array("label"=>"邮箱"))->add('marks', PercentType::class,array("label"=>"百分比"))->add('sports', CheckboxType::class, array('label'=>'是否班干部','required'=>false,))->add('photo', FileType::class, array('label' => '图片(格式:png, jpeg)'))->add('save', SubmitType::class, array('label'=>'提交'))->getForm();$form->handleRequest($request);if ($form->isSubmitted() && $form->isValid()) {$file = $task->getPhoto();$fileName = md5(uniqid()).'.'.$file->getClientOriginalExtension();$file->move($this->getParameter('photos_directory'), $fileName);$task->setPhoto($fileName);return new Response("上传成功");die;}else{//渲染return $this->render('default/form_test.html.twig', array('form' => $form->createView(),));}}
}

结果:

完整代码:

完整类:

<?php
namespace AppBundle\Entity;class Task
{private $studentName;private $studentId;public $password;private $address;public $joined;public $gender;private $email;private $marks;public $sports;public $photo;public function getUserName() {return $this->studentName;}public function setUserName($studentName) {$this->studentName = $studentName;}public function getUserId() {return $this->studentId;}public function setUserId($studentid) {$this->studentid = $studentid;}public function getAddress() {return $this->address;}public function setAddress($address) {$this->address = $address;}public function getEmail() {return $this->email;}public function setEmail($email) {$this->email = $email;}public function getMarks() {return $this->marks;}public function setMarks($marks) {$this->marks = $marks;}public function getPhoto() {return $this->photo;}public function setPhoto($photo) {$this->photo = $photo;return $this;}
}
?>

完整控制器:

<?phpnamespace AppBundle\Controller;//命名空间use AppBundle\Entity\Task;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;//路由文件
use Symfony\Bundle\FrameworkBundle\Controller\Controller;//基础控制器
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\DateType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\PasswordType;
use Symfony\Component\Form\Extension\Core\Type\EmailType;
use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
use Symfony\Component\Form\Extension\Core\Type\PercentType;
use Symfony\Component\Form\Extension\Core\Type\RepeatedType;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Form\Extension\Core\Type\FileType;
use AppBundle\Form\FormValidationType;
use Symfony\Component\HttpFoundation\Response;//基础类
class TestController extends Controller
{/*** 一定要写,定义路由(page表示参数,requirements表示数据验证)* @Route("/test/index/{page}&{limit}", name = "test_index", requirements = {"page": "\d+"})*/public function indexAction($page="",$limit="") {echo "Hellow word"."<br />";echo "获取参数1:".$page."<br />";echo "获取参数2:".$limit;die;}/*** @Route("/test/jump")*/public function jump(){echo "当前方法是:jump";return $this->redirect("/test/index/2&10");die;}/*** @Route("/test/template_en")*/public function template_en(){return $this->render("default/test.html.twig",['controller_name' => "Test",'func_name' => "template_en",]);}/*** @Route("/test/form_test")*/public function form_test(Request $request){//初始化对象$task = new Task();//创建$form = $this->createFormBuilder($task)->add('UserName', TextType::class,array('label'=>'姓名'))->add('UserId', TextType::class,array('label'=>'ID'))->add('password', RepeatedType::class, array('type'=>PasswordType::class,'invalid_message'=>'请填写密码','options'=>array('attr'=>array('class'=>'password-field')),'required'=>true,'first_options'=> array('label'=>'密码'),'second_options'=>array('label'=>'确认密码'),))->add('address', TextareaType::class,array('label'=>'地址'))->add('joined', DateType::class, array('widget'=>'choice','label'=>'生日'))->add('gender', ChoiceType::class,array('choices'=> array('男'=>true,'女'=>false,),'label'=>'性别'))->add('email', EmailType::class,array("label"=>"邮箱"))->add('marks', PercentType::class,array("label"=>"百分比"))->add('sports', CheckboxType::class, array('label'=>'是否班干部','required'=>false,))->add('photo', FileType::class, array('label' => '图片(格式:png, jpeg)'))->add('save', SubmitType::class, array('label'=>'提交'))->getForm();$form->handleRequest($request);if ($form->isSubmitted() && $form->isValid()) {$file = $task->getPhoto();$fileName = md5(uniqid()).'.'.$file->getClientOriginalExtension();$file->move($this->getParameter('photos_directory'), $fileName);$task->setPhoto($fileName);return new Response("上传成功");die;}else{//渲染return $this->render('default/form_test.html.twig', array('form' => $form->createView(),));}}}

完整页面:

{% extends 'base.html.twig' %}
{% block javascripts %}<script language = "javascript" src = "https://code.jquery.com/jquery-2.2.4.min.js"></script>
{% endblock %}{% block body %}<h3>表单示例</h3><div id="simpleform">{{ form_start(form) }}{{ form_widget(form) }}{{ form_end(form) }}</div>
{% endblock %}{% block stylesheets %}<style>h3{text-align: center;}#simpleform {width:50%;border:2px solid grey;padding:14px;margin-left: 25%;}#simpleform label {font-size:14px;float:left;width:300px;text-align:right;display:block;}#simpleform span {font-size:11px;color:grey;width:100px;text-align:right;display:block;}#simpleform input {border:1px solid grey;font-family:verdana;font-size:14px;color:light blue;height:24px;margin: 0 0 10px 10px;}#simpleform textarea {border:1px solid grey;font-family:verdana;font-size:14px;color:light blue;height:120px;width:250px;margin: 0 0 20px 10px;}#simpleform select {margin: 0 0 20px 10px;}#simpleform button {clear:both;margin-left:30%;background: grey;color:#FFFFFF;border:solid 1px #666666;font-size:16px;width: 20rem;}</style>
{% endblock %}

这篇关于PHP框架详解 - symfony框架的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/680849

相关文章

idea的终端(Terminal)cmd的命令换成linux的命令详解

《idea的终端(Terminal)cmd的命令换成linux的命令详解》本文介绍IDEA配置Git的步骤:安装Git、修改终端设置并重启IDEA,强调顺序,作为个人经验分享,希望提供参考并支持脚本之... 目录一编程、设置前二、前置条件三、android设置四、设置后总结一、php设置前二、前置条件

python中列表应用和扩展性实用详解

《python中列表应用和扩展性实用详解》文章介绍了Python列表的核心特性:有序数据集合,用[]定义,元素类型可不同,支持迭代、循环、切片,可执行增删改查、排序、推导式及嵌套操作,是常用的数据处理... 目录1、列表定义2、格式3、列表是可迭代对象4、列表的常见操作总结1、列表定义是处理一组有序项目的

python使用try函数详解

《python使用try函数详解》Pythontry语句用于异常处理,支持捕获特定/多种异常、else/final子句确保资源释放,结合with语句自动清理,可自定义异常及嵌套结构,灵活应对错误场景... 目录try 函数的基本语法捕获特定异常捕获多个异常使用 else 子句使用 finally 子句捕获所

C++11范围for初始化列表auto decltype详解

《C++11范围for初始化列表autodecltype详解》C++11引入auto类型推导、decltype类型推断、统一列表初始化、范围for循环及智能指针,提升代码简洁性、类型安全与资源管理效... 目录C++11新特性1. 自动类型推导auto1.1 基本语法2. decltype3. 列表初始化3

SQL Server 中的 WITH (NOLOCK) 示例详解

《SQLServer中的WITH(NOLOCK)示例详解》SQLServer中的WITH(NOLOCK)是一种表提示,等同于READUNCOMMITTED隔离级别,允许查询在不获取共享锁的情... 目录SQL Server 中的 WITH (NOLOCK) 详解一、WITH (NOLOCK) 的本质二、工作

springboot自定义注解RateLimiter限流注解技术文档详解

《springboot自定义注解RateLimiter限流注解技术文档详解》文章介绍了限流技术的概念、作用及实现方式,通过SpringAOP拦截方法、缓存存储计数器,结合注解、枚举、异常类等核心组件,... 目录什么是限流系统架构核心组件详解1. 限流注解 (@RateLimiter)2. 限流类型枚举 (

Java Thread中join方法使用举例详解

《JavaThread中join方法使用举例详解》JavaThread中join()方法主要是让调用改方法的thread完成run方法里面的东西后,在执行join()方法后面的代码,这篇文章主要介绍... 目录前言1.join()方法的定义和作用2.join()方法的三个重载版本3.join()方法的工作原

Spring AI使用tool Calling和MCP的示例详解

《SpringAI使用toolCalling和MCP的示例详解》SpringAI1.0.0.M6引入ToolCalling与MCP协议,提升AI与工具交互的扩展性与标准化,支持信息检索、行动执行等... 目录深入探索 Spring AI聊天接口示例Function CallingMCPSTDIOSSE结束语

C语言进阶(预处理命令详解)

《C语言进阶(预处理命令详解)》文章讲解了宏定义规范、头文件包含方式及条件编译应用,强调带参宏需加括号避免计算错误,头文件应声明函数原型以便主函数调用,条件编译通过宏定义控制代码编译,适用于测试与模块... 目录1.宏定义1.1不带参宏1.2带参宏2.头文件的包含2.1头文件中的内容2.2工程结构3.条件编

PyTorch中的词嵌入层(nn.Embedding)详解与实战应用示例

《PyTorch中的词嵌入层(nn.Embedding)详解与实战应用示例》词嵌入解决NLP维度灾难,捕捉语义关系,PyTorch的nn.Embedding模块提供灵活实现,支持参数配置、预训练及变长... 目录一、词嵌入(Word Embedding)简介为什么需要词嵌入?二、PyTorch中的nn.Em