首先说一下为什么要写symfony框架,这个框架也属于PHP的一个框架,小编接触也是3年前,原因是小编接触Golang,发现symfony框架有PHP框架的东西也有Golang的东西,所以决定总结一下,有需要的同学可以参看小编的Golang相关博客,看完之后在学习symfony效果更佳
symfony安装
3版本安转:
composer create-project symfony/framework-standard-edition symfony
php bin/console server:run
4版本安装:
composer create-project symfony/skeleton symfony
composer require --dev symfony/web-server-bundle
php bin/console server:start
控制器:
创建地址:symfonysrcAppBundleControllerTestController.php
<?php
namespace AppBundleController;//命名空间
use SensioBundleFrameworkExtraBundleConfigurationRoute;//路由文件
use SymfonyBundleFrameworkBundleControllerController;//基础控制器
//基础类
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表单,具体代码如下:
类:
地址:symfonysrcAppBundleEntityTask.php
<?php
namespace AppBundleEntity;
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;
}
}
?>
控制器:
地址:symfonysrcAppBundleControllerTestController.php
<?php
namespace AppBundleController;//命名空间
use SymfonyComponentFormExtensionCoreTypeChoiceType;
use SymfonyComponentFormExtensionCoreTypePasswordType;
use SymfonyComponentFormExtensionCoreTypeEmailType;
use SymfonyComponentFormExtensionCoreTypeCheckboxType;
use SymfonyComponentFormExtensionCoreTypeTextareaType;
use SymfonyComponentFormExtensionCoreTypePercentType;
use SymfonyComponentFormExtensionCoreTypeRepeatedType;
use SymfonyComponentHttpFoundationRequest;
//基础类
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(),
));
}
}
页面:
地址:symfonyappResourcesviewsdefaultform_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(AppBundleEntityTask)#2714 (10)
{
["studentName":"AppBundleEntityTask":private]=> string(1) "1"
["studentId":"AppBundleEntityTask":private]=> NULL
["password"]=> string(7) "3456789"
["address":"AppBundleEntityTask":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":"AppBundleEntityTask":private]=> string(8) "6@qq.com"
["marks":"AppBundleEntityTask":private]=> float(0.07)
["sports"]=> bool(true)
["studentid"]=> string(1) "2"
}
文件上传:
修改配置文件:
打开扩展:php.ini extension=php_fileinfo.dll
修改配置文件:symfonyappconfigconfig.yml
类:
<?php
namespace AppBundleEntity;
class Task
{
public $photo;
public function getPhoto() {
return $this->photo;
}
public function setPhoto($photo) {
$this->photo = $photo;
return $this;
}
}
?>
控制器:
<?php
namespace AppBundleController;//命名空间
//基础类
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 AppBundleEntity;
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;
}
}
?>
完整控制器:
<?php
namespace AppBundleController;//命名空间
use AppBundleEntityTask;
use SensioBundleFrameworkExtraBundleConfigurationRoute;//路由文件
use SymfonyBundleFrameworkBundleControllerController;//基础控制器
use SymfonyComponentFormExtensionCoreTypeTextType;
use SymfonyComponentFormExtensionCoreTypeDateType;
use SymfonyComponentFormExtensionCoreTypeSubmitType;
use SymfonyComponentFormExtensionCoreTypeChoiceType;
use SymfonyComponentFormExtensionCoreTypePasswordType;
use SymfonyComponentFormExtensionCoreTypeEmailType;
use SymfonyComponentFormExtensionCoreTypeCheckboxType;
use SymfonyComponentFormExtensionCoreTypeTextareaType;
use SymfonyComponentFormExtensionCoreTypePercentType;
use SymfonyComponentFormExtensionCoreTypeRepeatedType;
use SymfonyComponentHttpFoundationRequest;
use SymfonyComponentFormExtensionCoreTypeFileType;
use AppBundleFormFormValidationType;
use SymfonyComponentHttpFoundationResponse;
//基础类
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 %}
原文地址:https://blog.csdn.net/masterphp/article/details/135994800
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如若转载,请注明出处:http://www.7code.cn/show_66651.html
如若内容造成侵权/违法违规/事实不符,请联系代码007邮箱:suwngjj01@126.com进行投诉反馈,一经查实,立即删除!