• Skip to main content
  • Skip to primary sidebar
  • Skip to footer
  • 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

CodeSamplez.com

Programming, Web development, Cloud Technologies

You are here: Home / Database / Transformation Between Doctrine Entity And MySQL Database

Transformation Between Doctrine Entity And MySQL Database

April 28, 2013 by Rana Ahsan Leave a Comment

doctrine orm

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 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)

You may also like

Filed Under: Database Tagged With: doctrine, php

About Rana Ahsan

Rana is a passionate software engineer/Technology Enthusiast.
Github: ranacseruet

Reader Interactions

Leave a Reply Cancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Primary Sidebar

Subscribe to Blog via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 3,774 other subscribers

Follow Us

  • Twitter
  • Facebook

Top Posts & Pages

  • How To Work With JSON In Node.js / JavaScript
    How To Work With JSON In Node.js / JavaScript
  • PHP HTML5 Video Streaming Tutorial
    PHP HTML5 Video Streaming Tutorial
  • Generate HTTP Requests using c#
    Generate HTTP Requests using c#
  • How To Work With C# Serial Port Communication
    How To Work With C# Serial Port Communication
  • LinQ Query With Like Operator
    LinQ Query With Like Operator
  • Using Supervisord Web Interface And Plugin
    Using Supervisord Web Interface And Plugin
  • Facebook C# API Tutorials
    Facebook C# API Tutorials
  • Getting Started With Smarty Template Engine
    Getting Started With Smarty Template Engine
  • How To Use Hotkeys/Keyboard Events In WPF Application Using C#
    How To Use Hotkeys/Keyboard Events In WPF Application Using C#
  • Utilizing Config File In C#.NET Application
    Utilizing Config File In C#.NET Application

Recent Posts

  • Building Auth With JWT – Part 2
  • Building Auth With JWT – Part 1
  • Document Your REST API Like A Pro
  • Understanding Golang Error Handling
  • Web Application Case Studies You Must Read

Tags

.net angularjs apache api audio auth authenticatin aws c# cloud server codeigniter deployment docker doctrine facebook git github golang htaccess html5 http javascript jwt linq mysql nodejs oop performance php phpmyadmin plugin process python regular expression scalability server smarty socket.io tfs tips unit-test utility web application wordpress wpf

Footer

Archives

Follow Us

  • Twitter
  • Facebook

Subscribe to Blog via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 3,774 other subscribers

Copyright © 2023