我有以下模型,或者当您称它们为实体时,我也有一个控制器,一切都在此操作中起作用,但是当我检查数据库时,没有用户。所以我很好奇我缺少的东西。因此,让我们从我拥有的开始时开始:
bootstrap.php
包含以下代码等。
...
/** ---------------------------------------------------------------- **/
// Lets Setup Doctrine.
/** ---------------------------------------------------------------- **/
require_once 'vendor/autoload.php';
$loader = require 'vendor/autoload.php';
DoctrineCommonAnnotationsAnnotationRegistry::registerLoader(array($loader, 'loadClass'));
use DoctrineORMToolsSetup;
use DoctrineORMEntityManager;
/**
* Set up Doctrine.
*/
class DoctrineSetup {
/**
* @var array $paths - where the entities live.
*/
protected $paths = array(APP_MODELS);
/**
* @var bool $isDevMode - Are we considered "in development."
*/
protected $isDevMode = false;
/**
* @var array $dbParams - The database paramters.
*/
protected $dbParams = null;
/**
* Constructor to set some core values.
*/
public function __construct(){
if (!file_exists('db_config.ini')) {
throw new Exception(
'Missing db_config.ini. You can create this from the db_config_sample.ini'
);
}
$this->dbParams = array(
'driver' => 'pdo_mysql',
'user' => parse_ini_file('db_config.ini')['DB_USER'],
'password' => parse_ini_file('db_config.ini')['DB_PASSWORD'],
'dbname' => parse_ini_file('db_config.ini')['DB_NAME']
);
}
/**
* Get the entity manager for use through out the app.
*
* @return EntityManager
*/
public function getEntityManager() {
$config = Setup::createAnnotationMetadataConfiguration($this->paths, $this->isDevMode, null, null, false);
return EntityManager::create($this->dbParams, $config);
}
}
/**
* Function that can be called through out the app.
*
* @return EntityManager
*/
function getEntityManager() {
$ds = new DoctrineSetup();
return $ds->getEntityManager();
}
/**
* Function that returns the conection to the database.
*/
function getConnection() {
$ds = new DoctrineSetup();
return $ds->getEntityManager()->getConnection();
}
...
现在,我们已经有学说设置了时间来创建模型(实体)并设置哪些字段可以而且不能空白,等等。
NOTE 在这一点上,您应该知道我不使用Symfony其他,而不是其组成部分,而不是在学说之上。我正在使用纤细的框架。因此,如果有任何建议是使用Symfony使用X或Y,请确保其组成部分。
Models/User.php
<?php
namespace ImageUploaderModels;
use DoctrineORMMapping as ORM;
use SymfonyComponentValidatorConstraints as Assert;
/**
* @ORMEntity
* @ORMTable(name="users", uniqueConstraints={
* @ORMUniqueConstraint(name="user", columns={"userName", "email"})}
* )
*/
class User {
/**
* @ORMId
* @ORMColumn(type="integer")
* @ORMGeneratedValue
*/
protected $id;
/**
* @ORMColumn(type="string", length=32, nullable=false)
* @AssertNotBlank()
*/
protected $firstName;
/**
* @ORMColumn(type="string", length=32, nullable=false)
* @AssertNotBlank()
*/
protected $lastName;
/**
* @ORMColumn(type="string", length=100, unique=true, nullable=false)
* @AssertNotBlank(
* message = "Username cannot be blank"
* )
*/
protected $userName;
/**
* @ORMColumn(type="string", length=100, unique=true, nullable=false)
* @AssertNotBlank(
* message = "Email field cannot be blank."
* )
* @AssertEmail(
* message = "The email you entered is invalid.",
* checkMX = true
* )
*/
protected $email;
/**
* @ORMColumn(type="string", length=500, nullable=false)
* @AssertNotBlank(
* message = "The password field cannot be empty."
* )
*/
protected $password;
/**
* @ORMColumn(type="datetime", nullable=true)
*/
protected $created_at;
/**
* @ORMColumn(type="datetime", nullable=true)
*/
protected $updated_at;
/**
* Get the value of Created At
*
* @return mixed
*/
public function getCreatedAt()
{
return $this->created_at;
}
/**
* Set the value of Created At
*
* @param mixed created_at
*
* @return self
*/
public function setCreatedAt(DateTime $created_at = null)
{
$this->created_at = $created_at;
return $this;
}
/**
* Get the value of Updated At
*
* @return mixed
*/
public function getUpdatedAt()
{
return $this->updated_at;
}
/**
* Set the value of Updated At
*
* @param mixed updated_at
*
* @return self
*/
public function setUpdatedAt(DateTime $updated_at = null)
{
$this->updated_at = $updated_at;
return $this;
}
/**
* Get the value of First Name
*
* @return mixed
*/
public function getFirstName()
{
return $this->firstName;
}
/**
* Set the value of First Name
*
* @param mixed firstName
*
* @return self
*/
public function setFirstName($firstName)
{
$this->firstName = $firstName;
return $this;
}
/**
* Get the value of Last Name
*
* @return mixed
*/
public function getLastName()
{
return $this->lastName;
}
/**
* Set the value of Last Name
*
* @param mixed lastName
*
* @return self
*/
public function setLastName($lastName)
{
$this->lastName = $lastName;
return $this;
}
/**
* Get the value of User Name
*
* @return mixed
*/
public function getUserName()
{
return $this->userName;
}
/**
* Set the value of User Name
*
* @param mixed userName
*
* @return self
*/
public function setUserName($userName)
{
$this->userName = $userName;
return $this;
}
/**
* Get the value of Email
*
* @return mixed
*/
public function getEmail()
{
return $this->email;
}
/**
* Set the value of Email
*
* @param mixed email
*
* @return self
*/
public function setEmail($email)
{
$this->email = $email;
return $this;
}
/**
* Set ths password.
*
* @param string password
*
* @return self
*/
public function setPassword($password) {
$this->password = password_hash($password, PASSWORD_DEFAULT);
return $this;
}
/**
* Check the users password against that which is enterd.
*
* @param string password
*
* @return bool
*/
public function checkPassword($password) {
if (password_hash($password, PASSWORD_DEFAULT) === $this->getPassword()) {
return true;
}
return false;
}
/**
* Return the password value.
*
* @return hash
*/
private function getPassword(){
return $this->password;
}
/**
* @ORMPrePersist
*/
public function setCreatedAtTimeStamp() {
if (is_null($this->getCreatedAt())) {
$this->setCreatedAt(new DateTime());
}
}
/**
* @ORMPreUpdate
*/
public function setUpdatedAtTimeStamp() {
if (is_null($this->getUpdatedAt())) {
$this->setUpdatedAt(new DateTime());
}
}
}
据我所知,上面的模型是正确的,我的意思是,当我运行"vendor/bin/doctrine migrations:migrate"
时,数据库表是创建的。
现在,所有这些都在哪里使用?它在称为createAction($params)
SignupController
的控制器中 **createAction($params)**
public static function createAction($params){
$postParams = $params->request()->post();
$flash = new Flash();
if ($postParams['password'] !== $postParams['repassword']) {
$flash->createFlash('error', 'Your passwords do not match.');
self::$createEncryptedPostParams($postParams);
$params->redirect('/signup/error');
}
$user = new User();
$user->setFirstName($postParams['firstname'])
->setLastName($postParams['lastname'])
->setUserName($postParams['username'])
->setEmail($postParams['email'])
->setPassword($postParams['password'])
->setCreatedAtTimeStamp();
$validator = Validator::createValidatorBuilder();
$validator->enableAnnotationMapping();
$errors = $validator->getValidator()->validate($user);
if (count($errors) > 0) {
foreach($errors as $error) {
$flash->createFlash(
$error->getPropertyPath() . 'error',
$error->getMessage()
);
}
self::createEncryptedPostParams($postParams);
$params->redirect('/signup/error');
}
$anyEncryptedErors = self::getEncryptedPostParams();
if ($anyEncryptedErors !== null) {
$anyEncryptedErors->destroy('error');
}
getEntityManager()->flush();
getEntityManager()->persist($user);
$flash->createFlash('success', ' You have signed up successfully! Please sign in!');
$params->redirect('/signin');
}
现在,如果您正确输入所有内容,我会显示成功的闪光并重定向您。此工作它重定向,它显示了一个闪存消息。但它的:
getEntityManager()->flush();
getEntityManager()->persist($user);
我认为行不通。为什么?因为在有关数据库上执行select * from users
,没有记录。
为什么?
持久后应执行齐平语句。因此代码应该是:
getEntityManager()->persist($user);
getEntityManager()->flush();
我也有一个类似的问题,并认为我会在这里发布。我正在创建一个实体,一切都正确响应,但是当我检查数据库时,没有创建记录。
刚将冲洗包装在try-catch
中并记录了错误。
$this->em->persist($insectLifeCycle);
try {
$this->em->flush();
} catch (Exception $error) {
$this->logger->debug($error);
}
事实证明,其中一个属性超出了其字符限制,数据库正在丢弃错误。还发现我需要改善错误处理....
正如Samiul Amin Shanto所说:
getEntityManager()->persist($user);
getEntityManager()->flush();
将是正确的方法,因为持续操作准备要存储在db和flush中的数据将所有更改刷到数据库。
如果您具有对象ID,然后数据库没有显示它,则可能具有"启动事务",然后您有插入,此后插入后,您将拥有一个"犯罪"。如果您的持久性和提交之间出现任何错误,则对象不会存储在您的数据库中。检查您的SYMFONY请求Profiler信息。您可以使用开发人员工具找到它并检查您的响应。