• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

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

php 搞代码 3年前 (2022-01-26) 18次浏览 已收录 0个评论

本文实例讲述了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.phpnamespace 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($user<p>+本文来源gao!%daima.com搞$代*!码9网(</p><strong>搞gaodaima代码</strong>Admin);    $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://symfony.com/doc/current/bundles/DoctrineFixturesBundle/index.html

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

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


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:Symfony2实现在doctrine中内置数据的方法_PHP

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址