Symfony2實現在doctrine中內建資料的方法_php執行個體

來源:互聯網
上載者:User

本文執行個體講述了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($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://symfony.com/doc/current/bundles/DoctrineFixturesBundle/index.html

本文永久地址:http://blog.it985.com/6662.html
本文出自 IT985部落格 ,轉載時請註明出處及相應連結。

更多關於PHP架構相關內容感興趣的讀者可查看本站專題:《php優秀開發架構總結》,《codeigniter入門教程》,《CI(CodeIgniter)架構進階教程》,《Yii架構入門及常用技巧總結》及《ThinkPHP入門教程》

希望本文所述對大家基於Symfony架構的PHP程式設計有所協助。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.