CodeSamplez.com

Programming, Web development, Cloud Technologies

  • 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

Rana Ahsan 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 🙂

Related

Filed Under: Database Tagged With: doctrine, php

About Rana Ahsan

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

Leave a Reply Cancel reply

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

Email Subscription

Never miss any programming tutorial again.

Popular Tutorials

  • How To Work With JSON In Node.js / JavaScript
  • PHP HTML5 Video Streaming Tutorial
  • How To Work With C# Serial Port Communication
  • LinQ Query With Like Operator
  • Facebook C# API Tutorials
  • LinQ To SQL Database Update Operations In C#
  • Using Supervisord Web Interface And Plugin
  • Tutorial On Uploading File With CodeIgniter Framework / PHP
  • Utilizing Config File In C#.NET Application
  • Getting Started With Smarty Template Engine

Recent Tutorials

  • Building Auth With JWT – Part 1
  • 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

Recent Comments

  • S. Chalisque on PHP HTML5 Video Streaming Tutorial
  • Armorik on Generate HTTP Requests using c#
  • iswaps on PHP HTML5 Video Streaming Tutorial
  • TAKONDWA on PHP HTML5 Video Streaming Tutorial
  • rorenzo on PHP HTML5 Video Streaming Tutorial

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 - 2022 · CodeSamplez.com ·

Copyright © 2022 · Streamline Pro Theme on Genesis Framework · WordPress · Log in