Data insertion with PHP OO (Similar to Entitymanager.persist (Object) java manager)

Asked

Viewed 114 times

1

I would like a tip on how to loop to insert an object into the mysql/ postgres database ...

Example

class User {
     // PRIMARY KEY
     public $id;
     public $login;
     // PRIMARY FOIREIGN KEY
     public $people;

     __construct() { 
         $this->id = -1;
         $this->login = "";
         $this->people = new People();  
    }
}




class People {
     // PRIMARY KEY
     public $id;
     public $name;

     __construct() { 
         $this->id = -1;
         $this->name = "";
    }
}


class Controller {

     $em = EntityManager();
     $em->beginTrasaction();
     $user = new User();
     $user->setLogin('admin');
     $bool = $em->persist($user);
     if($bool) {
          $em->commit();
     } else {
          $em->rollBack();
     }
}

1 answer

1

It exists just like the Java Hibernate framework, php frameworks for ORM one that I started using a little while ago, but today I do not give up is Doctrine (ORM Framework) through it you can define your entity by mapping the class with comments (similar to Java Annotations), see how to work with objects in Doctrine. I believe this is what you’re looking for. Regarding the use of the SGDB you are using, you just have to configure the connection (similar to the driver in the case of Hibernate) done this. If you use the conventions established by Doctrine (in general they are similar to Hibernate) you can port your application to other databases without difficulties. As I said before, there are other ORM frameworks, but what I know and like is Doctrine.

Once using Doctrine, configured the database connection and added the annotations in the entity, you loop create the instances, assign the values and execute the command below to save the data in the persistence layer.

$em->persist($user); //considerando $em o entity manager do doctrine
$em->flush();
  • I managed to solve the situation without using Doctrine I thank you for the answer and the solution.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.