当前位置: 移动技术网 > IT编程>开发语言>PHP > Symfony2实现在doctrine中内置数据的方法

Symfony2实现在doctrine中内置数据的方法

2017年12月12日  | 移动技术网IT编程  | 我要评论

召集大地之环,l姓小鲜肉有谁,信誉群

本文实例讲述了symfony2实现在doctrine中内置数据的方法。分享给大家供大家参考,具体如下:

我们在使用symfony的时候,有时需要在数据库中内置一些数据,那么我们如何在doctrine中设置呢?

所幸,symfony已经为我们封装好了。这里,我们需要用到doctrinefixturesbundle。

第一步,在composer.json中引入所需的doctrinefixturesbundle:

{
  "require": {
    "doctrine/doctrine-fixtures-bundle": "2.2.*"
  }
}

第二步,执行composer:

composer update doctrine/doctrine-fixtures-bundle

第三步,在内核(app/appkernel.php)中注册此bundle:

// ...
public function registerbundles()
{
  $bundles = array(
    // ...
    new doctrine\bundle\fixturesbundle\doctrinefixturesbundle(),
    // ...
  );
  // ...
}

第四步,在需要内置数据的bundle下创建一个php类文件,如src/acme/hellobundle/datafixtures/orm/loaduserdata.php,其代码如下:

// src/acme/hellobundle/datafixtures/orm/loaduserdata.php
namespace acme\hellobundle\datafixtures\orm;
use doctrine\common\datafixtures\fixtureinterface;
use doctrine\common\persistence\objectmanager;
use acme\hellobundle\entity\user;
class loaduserdata implements fixtureinterface
{
  /**
   * {@inheritdoc}
   */
  public function load(objectmanager $manager)
  {
    $useradmin = new user();
    $useradmin->setusername('admin');
    $useradmin->setpassword('test');
    $manager->persist($useradmin);
    $manager->flush();
  }
}

第五步,通过console执行内置数据命令:

php app/console doctrine:fixtures:load #为防止数据库中原先的值被清除,可使用 --append 参数

此命令有以下三个参数:

fixtures=/path/to/fixture – use this option to manually specify the directory where the fixtures classes should be loaded;
append – use this flag to append data instead of deleting data before loading it (deleting first is the default behavior);
em=manager_name – manually specify the entity manager to use for loading the data.

官方文档:

本文永久地址:http://blog.it985.com/6662.html
本文出自 it985博客 ,转载时请注明出处及相应链接。

更多关于php框架相关内容感兴趣的读者可查看本站专题:《php优秀开发框架总结》,《codeigniter入门教程》,《ci(codeigniter)框架进阶教程》,《yii框架入门及常用技巧总结》及《thinkphp入门教程

希望本文所述对大家基于symfony框架的php程序设计有所帮助。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网