model是MVC里的M
model的读取流程:数据库表=>model类实例=>controller透传=>前端展示
感觉没有python的peewee模块简洁
创建一个model创建文件:src/AppBundle/Entity/BlogPost.php
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* BlogPost
*
* @ORM\Table()
* @ORM\Entity
*/
class BlogPost
{
/**
* @var integer
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @var string
*
* @ORM\Column(name="title", type="string", length=255)
*/
private $title;
/**
* @var string
*
* @ORM\Column(name="body", type="text")
*/
private $body;
/**
* @var \DateTime
*
* @ORM\Column(name="create_time", type="datetime")
*/
private $createTime;
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set title
*
* @param string $title
* @return BlogPost
*/
public function setTitle($title)
{
$this->title = $title;
return $this;
}
/**
* Get title
*
* @return string
*/
public function getTitle()
{
return $this->title;
}
/**
* Set body
*
* @param string $body
* @return BlogPost
*/
public function setBody($body)
{
$this->body = $body;
return $this;
}
/**
* Get body
*
* @return string
*/
public function getBody()
{
return $this->body;
}
/**
* @return \DateTime
*/
public function getCreateTime()
{
return $this->createTime;
}
/**
* @param \DateTime $createTime
*/
public function setCreateTime($createTime)
{
$this->createTime = $createTime;
}
}
说明:
BlogPost这个model从含义上表达了一篇博客,从实现上表达了数据库表的一行,有id、title、body、createTime几个属性,其中id是数据库的主键(自增1,不需要setId方法),title是博客的标题,body是博客内容,createTime是博客创建时间
数据库配置app/config/parameters.yml文件
parameters:
database_host: 127.0.0.1
database_port: 3306
database_name: mywebsite
database_user: root
database_password: shareditor@126.COM
mailer_transport: smtp
mailer_host: 127.0.0.1
mailer_user: null
mailer_password: null
secret: 1a0cb131fb193436d0f6ce467f2d8b6c7c5b02da
app/console工具
$ php app/console doctrine:database:create # 初始化数据库
$ php app/console doctrine:schema:update --force # 新建数据表
手工往数据库里插入一行数据
mysql> insert into blog_post(title,body,create_time) values('这是标题','这是内容',now());
model的读取
src/AppBundle/Controller/BlogController.php中的showAction方法
public function showAction(Request $request)
{
$blogPostRepository = $this->getDoctrine()->getRepository('AppBundle:BlogPost');
$blogposts = $blogPostRepository->findAll();
return $this->render('blog/show.html.twig', array('title' => $blogposts[0]->getTitle(), 'content' => $blogposts[0]->getBody()));
}
app/Resources/views/blog/show.html.twig
{% extends "base.html.twig" %}
{% block title %}博客内容{% endblock title %}
{% block body %}
<div class="row jumbotron">
<div class="col-md-1 col-xs-1"></div>
<div class="col-md-10 col-xs-10"><h1>{{ title }}</h1></div>
<div class="col-md-1 col-xs-1"></div>
</div>
<div class="row">
<div class="col-md-1 col-xs-1"></div>
<div class="col-md-10 col-xs-10"><h4>{{ content }}</h4></div>
<div class="col-md-1 col-xs-1"></div>
</div>
{% endblock body %}
参考:
MVC模式中的Model使用方法