过上一个博客系统以及对官方示例程序的基本学习,目前对symfony的各个组件有了一定的学习,学校布置了一个表白墙任务,这里就这个任务的完成进行记录
...........2019.3.20.22.31基本写完了,感觉像一坨屎,等我明天对symfony的细节再进行学习一下,重构一下,应该有很多好用的组件我不是很熟悉的,感觉这次写的还没有上一个任务用原生php+mysql写的逻辑性强一点,后续用第三方包knppaginatorBundle进行了分页功能的实现,这个网上很多博客都说过了,这里不再赘述,然后用表格显示了数据能好看一点了起码,不写前端,能看懂就行,这里没必要去研究,。。。。因为命名不规范还出现个小bug,无法正常跳转页面,,,命名不规范,亲人两行泪啊
分页链接见:https://www.cnblogs.com/zgaspnet/p/7640330.html
先看具体任务
使用staruml先确定数据库表内容以及表关系,这里比较简单就两个表,不需要用户表,匿名进行的,记录用户ip地址即可,
好了,确定好了之后,下面开始进行源码编写,let's do it!
为了达到练习的目的,这里一步一步的完成它,
首先使用 php symfony new Expression "3.4.2" -vvv 创建symfony 3.4.2版本的应用程序,之后可能会用到其他的库,为了安装速度,这里先安装下composer国内镜像
composer config repo.packagist composer https://packagist.phpcomposer.com //执行此命令即可
接下来编写Entity,Comment和LoveExpress
<?php namespace AppBundleEntity; use DoctrineORMMapping as ORM; use SymfonyComponentValidatorConstraints as Assert; /** * @ORMEntity(repositoryClass = "AppBundleRepositoryCommentRepository") * @ORMTable(name = "comment") */ class Comment{ /** * @ORMId * @ORMColumn(type="integer") * @ORMGeneratedValue(strategy="AUTO") */ private $id; /** * @ORMColumn(type="text") * @AssertLength( * min = 5, * minMessage="comment.too_short", * max =400, * maxMessage = "comment.too_long" * ) */ private $content; /** * @ORMManyToOne(targetEntity = "LoveExpress",inversedBy="comments") * @ORMJoinColumn(name="expression_id",referencedColumnName="id") */ protected $expression; }
<?php namespace AppBundleEntity; use DoctrineORMMapping as ORM; use SymfonyComponentValidatorConstraints as Assert; //验证数据是否合法 use DoctrineCommonCollectionsArrayCollection; use DoctrineORMOneToMany; /** * @ORMEntity(repositoryClass="AppBundleRepositoryLoveExpressRepository") * @ORMTable(name = "love_express") */ class LoveExpress{ /** * @ORMId * @ORMGeneratedValue(strategy="AUTO") * @ORMColumn(type="integer") */ private $id; /** * @ORMColumn(type="text") * @AssertLength( * min=5, * minMessage="comment.too_short", * max=10000, * maxMessage="comment.too_long" * ) */ private $content; /** * @ORMColumn(type="string") */ private $user_ip; /** * 点赞数 * @ORMColumn(type="integer",default=0) */ private $number_up; /** * 踩一踩的数量 * @ORMColumn(type="integer",default=0) */ private $number_down; /** * @ORMOneToMany(tegetEntity="LoveExpress",mappedBy="expression") */ protected $comments; public function __construct() { $this->comments = new ArrayCollection(); } }
接下来在app/config文件当中进行数据库配置,具体因人而异
再执行命令php bin/console doctrine:schema:validate 检查annoation是否有错误,最好执行这一步,不然你哪块少个字母会出现难以发现的错误
接着 php bin/console doctrine:create:database 创建数据库这里的名字为expresswall
这里创建之前先说明一下,在mysql目录下的my.cnf文件中加入下列代码,设置正确的字符集,校对集,以免后面产生未知bug
collation-server = utf8mb4_general_ci # Replaces utf8_general_ci character-set-server = utf8mb4 # Replaces utf
或者加入下列代码到app/config的doctrine下面
charset: utf8mb4 default_table_options: charset: utf8mb4 collate: utf8mb4_unicode_ci
php bin/console doctrine:generate:entities AppBundle 补全entity实例
接下来进行控制器的编写,我准备先使用DoctirneFixture对数据库进行初始化,在此之前先进行安装,不赘述
艹草草哦啊哦草 气死了真的,mysql好好的突然不能用了,真的很奇怪,刚开始以为是哪里写错了,结果从新创个项目也是不行,最后发现net start mysql 启动失败,并且没有错误原因,经查找决定初始化下
先重新创建data文件,记着保存数据库,真的很奇怪为什么莫名其妙不行了
mysqld -remove
mysqld -install
mysqld --initialize
之后再从新启动就行了
一下子做了很多,遇到了很多问题,暂时没有很好地解决方法,前端根本不会写,我想用国外的一个HTML组件对前端进行重写下,等到基本功能都实现了,
下面是评论和主页面的控制器,感觉写的跟个屎一样,先做完基本功能之后再进行从写吧,
ActionController
<?php
namespace AppBundleController;
use SensioBundleFrameworkExtraBundleConfigurationRoute;
use SymfonyBundleFrameworkBundleControllerController;
use SymfonyComponentFormExtensionCoreTypeSubmitType;
use SymfonyComponentHttpFoundationRequest;
use AppBundleEntityLoveExpress;
use AppBundleEntityComment;
use SymfonyComponentFormExtensionCoreTypeTextType;
//主页面
/**
* @Route("/love")
*/
class ActionController extends Controller
{
/**
* 获取comment和loveExpress的repository
* @return AppBundleRepositoryCommentRepository
*/
protected function getCommentRepository(){
$em = $this->getDoctrine()->getManager();
$commentRes = $em->getRepository(Comment::class);
return $commentRes;
}
/**
* @return AppBundleRepositoryLoveExpressRepository
*/
protected function getLoveExpressRepository()
{
$em = $this->getDoctrine()->getManager();
$love = $em->getRepository(LoveExpress::class);
return $love;
}
/**
* 主控制器,用于从数据库当中获取数据并且返回给homepage模板,
* @Route("/index/{page}", name="homepage",defaults={"page":"1"})
*/
public function indexAction($page)
{
$loveExpress = $this->getLoveExpressRepository()->createQueryBuilder('u');
$paginator = $this->get('knp_paginator');
$pagination = $paginator->paginate($loveExpress, $page,3);
return $this->render('love/index.html.twig',
array('loveExpress'=>$pagination)
);
}
/**
* 获取单个表白信息并进行显示,并返回评论表单
* @Route("/show/{id}",name="loveShow")
* */
public function showAction($id, Request $request){
$loveRes = $this->getLoveExpressRepository();
$loveExpress = $loveRes->find($id);
$commentRes = $this->getCommentRepository();
$comments = $commentRes->findBy(array("expression"=>$id));
//创建评论表单并更新
$comment = new Comment();
$comment->setExpression($loveExpress);
$form = $this->createFormBuilder($comment)
->add('content',TextType::class)
->add('发布评论',SubmitType::class)
->getForm();
$form->handleRequest($request); //处理请求
if($form->isValid() && $form->isSubmitted()){
$em = $this->getDoctrine()->getManager();
$em->persist($comment);
$em->flush();
return $this->redirectToRoute('loveShow',array('id'=>$id));
}
return $this->render(
"love/show.html.twig",
array('loveExpress'=>$loveExpress,
'comments'=>$comments,
'form'=>$form->createView()
)
);
}
/**
* 执行点赞或者踩一踩操作
* @Route("/down/{id}/{action}",name="love_action")
*/
public function loveUpDownAction($id,$action){
$loveRes = $this->getLoveExpressRepository();
$loveExpress = $loveRes->find($id);
if($action == 'down'){
$loveExpress->setNumberDown(($loveExpress->getNumberDown()+1));
}else{
$loveExpress->setNumberUp(($loveExpress->getNumberUp() + 1));
}
$em = $this->getDoctrine()->getManager();
$em->persist($loveExpress);
$em->flush();
return $this->redirectToRoute('loveShow',array('id'=>$id));
}
}
NewController
<?php /** * Created by PhpStorm. * User: 亦清 * Date: 2019/3/19 * Time: 10:22 */ namespace AppBundleController; use SymfonyBundleFrameworkBundleControllerController; use SensioBundleFrameworkExtraBundleConfigurationRoute; use SymfonyComponentFormExtensionCoreTypeSubmitType; use SymfonyComponentHttpFoundationRequest; use SymfonyComponentFormExtensionCoreTypeTextType; use AppBundleEntityLoveExpress; /** * @Route("/love") */ class NewController extends Controller { function getRealIp() { $ip=false; if(!empty($_SERVER["HTTP_CLIENT_IP"])){ $ip = $_SERVER["HTTP_CLIENT_IP"]; } if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) { $ips = explode (", ", $_SERVER['HTTP_X_FORWARDED_FOR']); if ($ip) { array_unshift($ips, $ip); $ip = FALSE; } for ($i = 0; $i < count($ips); $i++) { if (!eregi ("^(10│172.16│192.168).", $ips[$i])) { $ip = $ips[$i]; break; } } } return ($ip ? $ip : $_SERVER['REMOTE_ADDR']); } /** * 增加表白信息,创建表单并返回给new.html.twig页面 * @Route("/newLove",name="newLove") */ public function addLoveAction(Request $request){ $love = new LoveExpress(); $form = $this->createFormBuilder($love) ->add('name') ->add('content',TextType::class) ->add('保存发布',SubmitType::class) ->getForm(); $form->handleRequest($request); //处理请求 if($form->isValid() && $form->isSubmitted()){ $love->setUserIp($this->getRealIp()); //获取并设置ip $em = $this->getDoctrine()->getManager(); $em->persist($love); $em->flush(); $this->addFlash('success','发布成功'); return $this->redirectToRoute('homepage'); } return $this->render( 'love/new.html.twig' ,array('form'=>$form->createView(),) ); } }
下面是twig模板
index.twig.html {% extends 'base.html.twig' %} {% block body %} <title>表白墙系统</title> <div style=" text-align:center;"> <h1>主页面</h1> <h2><a href="{{ path('newLove') }}">发布表白信息</a></h2> {% for love in loveExpress %} <h4>发布游客名称:{{ love.name }}</h4> <p> <a href={{ path('loveShow',{"id":love.id}) }}>{{ love.content|md2html|striptags|slice(0,30) }}..显示全部</a> </p> {% endfor %} </div> {% endblock %} new.html.twig {% extends "base.html.twig" %} {% block body %} <div class="text" style=" text-align:center;"> <h1>发布表白页面</h1> {{ form_start(form) }} {{ form_row(form.name) }} {{ form_row(form.content) }} {{ form_end(form) }} </div> {% endblock %} show.html.twig {% extends "base.html.twig" %} {% block body %} <div class="text" style=" text-align:center;"> <h1>发布表白页面</h1> {{ form_start(form) }} {{ form_row(form.name) }} {{ form_row(form.content) }} {{ form_end(form) }} </div> {% endblock %}