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

相关文章

C语言函数递归实际应用举例详解

《C语言函数递归实际应用举例详解》程序调用自身的编程技巧称为递归,递归做为一种算法在程序设计语言中广泛应用,:本文主要介绍C语言函数递归实际应用举例的相关资料,文中通过代码介绍的非常详细,需要的朋... 目录前言一、递归的概念与思想二、递归的限制条件 三、递归的实际应用举例(一)求 n 的阶乘(二)顺序打印

Python Faker库基本用法详解

《PythonFaker库基本用法详解》Faker是一个非常强大的库,适用于生成各种类型的伪随机数据,可以帮助开发者在测试、数据生成、或其他需要随机数据的场景中提高效率,本文给大家介绍PythonF... 目录安装基本用法主要功能示例代码语言和地区生成多条假数据自定义字段小结Faker 是一个 python

Java Predicate接口定义详解

《JavaPredicate接口定义详解》Predicate是Java中的一个函数式接口,它代表一个判断逻辑,接收一个输入参数,返回一个布尔值,:本文主要介绍JavaPredicate接口的定义... 目录Java Predicate接口Java lamda表达式 Predicate<T>、BiFuncti

详解如何通过Python批量转换图片为PDF

《详解如何通过Python批量转换图片为PDF》:本文主要介绍如何基于Python+Tkinter开发的图片批量转PDF工具,可以支持批量添加图片,拖拽等操作,感兴趣的小伙伴可以参考一下... 目录1. 概述2. 功能亮点2.1 主要功能2.2 界面设计3. 使用指南3.1 运行环境3.2 使用步骤4. 核

一文详解JavaScript中的fetch方法

《一文详解JavaScript中的fetch方法》fetch函数是一个用于在JavaScript中执行HTTP请求的现代API,它提供了一种更简洁、更强大的方式来处理网络请求,:本文主要介绍Jav... 目录前言什么是 fetch 方法基本语法简单的 GET 请求示例代码解释发送 POST 请求示例代码解释

详解nginx 中location和 proxy_pass的匹配规则

《详解nginx中location和proxy_pass的匹配规则》location是Nginx中用来匹配客户端请求URI的指令,决定如何处理特定路径的请求,它定义了请求的路由规则,后续的配置(如... 目录location 的作用语法示例:location /www.chinasem.cntestproxy

CSS will-change 属性示例详解

《CSSwill-change属性示例详解》will-change是一个CSS属性,用于告诉浏览器某个元素在未来可能会发生哪些变化,本文给大家介绍CSSwill-change属性详解,感... will-change 是一个 css 属性,用于告诉浏览器某个元素在未来可能会发生哪些变化。这可以帮助浏览器优化

Python基础文件操作方法超详细讲解(详解版)

《Python基础文件操作方法超详细讲解(详解版)》文件就是操作系统为用户或应用程序提供的一个读写硬盘的虚拟单位,文件的核心操作就是读和写,:本文主要介绍Python基础文件操作方法超详细讲解的相... 目录一、文件操作1. 文件打开与关闭1.1 打开文件1.2 关闭文件2. 访问模式及说明二、文件读写1.

详解C++中类的大小决定因数

《详解C++中类的大小决定因数》类的大小受多个因素影响,主要包括成员变量、对齐方式、继承关系、虚函数表等,下面就来介绍一下,具有一定的参考价值,感兴趣的可以了解一下... 目录1. 非静态数据成员示例:2. 数据对齐(Padding)示例:3. 虚函数(vtable 指针)示例:4. 继承普通继承虚继承5.

前端高级CSS用法示例详解

《前端高级CSS用法示例详解》在前端开发中,CSS(层叠样式表)不仅是用来控制网页的外观和布局,更是实现复杂交互和动态效果的关键技术之一,随着前端技术的不断发展,CSS的用法也日益丰富和高级,本文将深... 前端高级css用法在前端开发中,CSS(层叠样式表)不仅是用来控制网页的外观和布局,更是实现复杂交