Symfony – How to call doctrine in an entity class using symfony

doctrine-ormentitysymfony

Am using symfony framework for my application. And to save records in database I want call the $this->getDoctrine()->getManager(); method in my entity class. But when I did that it gave me the error:
Call to undefined method getDoctrine(),

Can some one tell me what is the right way to do this.

My entity class is like:

namespace Acme\SuperbAppBundle\Entity;

use Symfony\Component\DependencyInjection\Container;
use Doctrine\ORM\Mapping as ORM;

class Users
{


/**
 * @var integer
 */
private $id;

/**
 * @var string
 */
private $firstName;

/**
 * @var string
 */

/**
 * Get id
 *
 * @return integer 
 */
public function getId()
{
    return $this->id;
}

/**
 * Set firstName
 *
 * @param string $firstName
 * @return Users
 */
public function setFirstName($firstName)
{
    $this->firstName = $firstName;

    return $this;
}

/**
 * Get firstName
 *
 * @return string 
 */
public function getFirstName()
{
    return $this->firstName;
}


function __construct($firstName){

    $this->setFirstName($firstName);

}

function save(){

    $em = $this->getDoctrine()->getManager();
    $em->persist($create);
    $em->flush();
}

}

And my controller method is like:

   public function test(){

    $create = new Users('Rajat');

    $create->save();

 }

Best Solution

Your save method is attempting to call

$this->getDoctrine();

Whereby $this is the current Class, and any other Class it inherits. As it stands, your current Class, User, is standalone, and does not have a getDoctrine() method. If your Class were to extend the Controller Class, it would have access to that method:

class User extends Controller

I believe this simple fix will work, although it probably doesn't make real sense for it to extend Controller, as it is a User Entity, and unrelated to a Controller. A preferred, more advanced method, would be to inject the Doctrine service into the User class.

Related Question