CodeSamplez

Programming Tutorials And Source Code Examples

  • Facebook
  • Google+
  • RSS
  • Twitter
  • Home
  • Featured
    • C# Tutorials
      • LinQ Tutorials
      • Facebook C# API Tutorials
    • PHP Tutorials
      • CodeIgniter Tutorials
    • Amazon AWS Tutorials
  • Categories
    • Programming
    • Development
    • Database
    • Web Server
    • Source Control
    • Management
    • Project
  • About
  • Write
  • Contact
Home Database Transformation Between Doctrine Entity And MySQL Database

Transformation Between Doctrine Entity And MySQL Database

Md Ali Ahsan Rana April 28, 2013 Leave a Comment


 Transformation Between Doctrine Entity And MySQL Database  
 


If you have started using doctrine ORM, you should already have the idea how tightly the database and doctrine entity are bonded together. Any kind of change must need to be reflected on doctrine entity and database itself as well. That can become a boring task if you start doing the changes on both side manually. So, its worth to figure out a way to migrate from one to another.

Entity To DB Or DB To Entity?

If you are a swift user of doctrine, you may know that, most doctrine users love to write entity first and then generate database schema from there. From my raw php/mysql background, I, at first, did made the relationships in database, then create entities from database. Time to time, I came to realize that it is not a proper or efficient ways as we might to write several custom codes/functionality inside entities. Then I get two options, either update both database and entity or figure out the way to generate/update database from entity. I did get used to it and now I am a lover of this strategy :D.
database documentation
This is beneficial in another way that, you can put some documentation, custom functional implementation and some advance relationship establishment which aren’t directly supported by doctrine’s EntityGenerator class.

However, in this small tutorial, I will show you both ways so that you can decide yourself which way to go. Lets get started.

Which Way, CLI Or PHP?

Well, it’s a personal choice and you can go for any one of them. I like through PHP, don’t have any strong evidence, just like it. So, I won’t cover the usage of CLI tool here. I will only explain how to do it through PHP script. But you can always start with the doctrine documentation on CLI tool.

Doctrine Entity Generator Script From Database:

I am assuming you already can connect and retrieve the entity manager. The following function will do the work of generating entities from connected database on given path place. This is helpful if you started integrating on an existing application which has a number of database tables. However, you only should call this function once, not every time. Lets see the function and I will explain the steps afterwards:

/**
   * generate entities from database
   * @return none
   */
  function generate_doctrine_entities($em,$path="Entities"){     
      
    $em->getConfiguration()
             ->setMetadataDriverImpl(
                new DatabaseDriver(
                        $this->em->getConnection()->getSchemaManager()
                )
    );

    $cmf = new DisconnectedClassMetadataFactory();
    $cmf->setEntityManager($em);
    $metadata = $cmf->getAllMetadata();     
    $generator = new EntityGenerator();
    
    $generator->setUpdateEntityIfExists(true);
    $generator->setGenerateStubMethods(true);
    $generator->setGenerateAnnotations(true);
    $generator->generate($metadata, $path);
    
  }

As you can see, first we are setting the metadata driver with schema manager.then retrieve all metadata. Finally, create entity generator class instance, and generate on the given path from the retrieved metadata info.

Create/Update Database Schema From Doctrine Entities:

This is the preferred approach for me. One of the best usage is, you can change your necessary changes anytime and reflect the changes to database through it, even if the database is live, as long as no conflicting data is there.

function create_update_database($em,$mode="update"){

            $tool = new \Doctrine\ORM\Tools\SchemaTool($em);

            $cmf = new \Doctrine\ORM\Tools\DisconnectedClassMetadataFactory();
            $cmf->setEntityManager($em);
            $metadata = $cmf->getAllMetadata();

            if($mode == "create"){
                $queries = $tool->getCreateSchemaSql($metadata);
            }
            else{
                $queries = $tool->getUpdateSchemaSql($metadata);
            }
            echo "Total queries: ".count($queries)."<br /><br />";
            for($i=0; $i<count($queries);$i++){
                $em->getConnection()->prepare($queries[$i])->execute();
                echo $queries[$i]."<br /><br />Execution Successful: ".($i+1)."<br /><br />";
            }
}

As you can see, we are using the metadatafactory class here as well and instead of ‘EntityGenrator’, we are using the Schematool class here. with help of this tools “getCreateSchemaSql” or “getUpdateSchemaSql” function, we can get the queries which are required to be executed.

Hopefully this small doctrine entity generation tutorial will help you in some extent on the way to doctrine based application development. Please use the comment box below if you have any questions/suggestions/feedback. Happy coding 🙂

Share If Liked

  • Click to share on Facebook (Opens in new window)
  • Click to share on Google+ (Opens in new window)
  • Click to share on Twitter (Opens in new window)
  • Click to share on LinkedIn (Opens in new window)
  • Click to share on Pinterest (Opens in new window)
  • Click to share on Reddit (Opens in new window)
  • Click to share on Tumblr (Opens in new window)
  • Click to share on Pocket (Opens in new window)

Related Tutorials:

Doctrine Relationship Management Between Entities Dctrine ORMBasics On Doctrine CRUD Operations doctrineHow To Execute Native SQL Query With Doctrine doctrine codeigniterHow To Use Doctrine With CodeIgniter

Filed Under: Database Tagged With: doctrine, php

About Md Ali Ahsan Rana

Rana is a passionate software engineer/Technology Enthusiast.

Twitter: @ranacseruet
Github: ranacseruet

Leave a Reply Cancel reply

Email Subscription

Never miss any programming tutorial again.

Popular Tutorials

  • Generate HTTP Requests using c#
  • How To Work With JSON In Node.js / JavaScript
  • How To Work With C# Serial Port Communication
  • PHP HTML5 Video Streaming Tutorial
  • How To Work With Multithreaded Programming In C#.NET Application
  • Tutorial On Uploading File With CodeIgniter Framework / PHP
  • 8 Most Frequently Used And Useful PHP Array Operations
  • Getting Started With CodeIgniter URL Routing
  • How To Work With CodeIgniter Forms
  • Getting Started With Using Dictionary Collection In C#
Follow Us On Twitter

Support The Site With A Click

CodeIgniterPlus
Codesamplez

Recent Tutorials

  • Document Your REST API Like A Pro
  • Understanding Golang Error Handling
  • Web Application Case Studies You Must Read
  • Getting Started With Golang Unit Testing
  • Getting Started With Big Data Analytics Pipeline
  • NodeJS Tips And Tricks For Beginners
  • Apple Push Notification Backend In NodeJS
  • Web Based Universal Language Translator, Voice/Text Messaging App
  • How To Dockerize A Multi-Container App From Scratch
  • Getting Started With NVML Python API

Recent Comments

  • Lucifa on PHP HTML5 Video Streaming Tutorial
  • azaz on Apple Push Notification Backend In NodeJS
  • visworlditsolution on Beginning Htaccess Programming
  • r.petroff on “Facebooksdk” – C#.NET Library For Facebook API
  • Gopakumar on How To Work With C# Serial Port Communication

Archives

Resources

  • CodeSamplez.com Demo

Tags

.net apache api audio aws c# cache cloud server codeigniter deployment doctrine facebook git github golang htaccess html5 http image java javascript linq mysql nodejs oop performance php phpmyadmin plugin process python regular expression scalability server smarty ssh tfs thread tips ubuntu unit-test utility web application wordpress wpf

Copyright © 2010 - 2018 · CodeSamplez.com ·

60000