Answer the question
In order to leave comments, you need to log in
How to write the necessary methods to work with the database?
Good day.
I recently started learning the wonderful symfony framework, version 2.8.
Faced a problem. I have a typical controller with action show:
(Here I take an entry from the database with a specific login)
/...
use AppBundle\Entity\People;
class DefaultController extends Controller {
public function showAction($login)
{
$em = $this->getDoctrine()->getManager();
$human = $em->getRepository("AppBundle:People")->findOneBy(["login" => $login]);
}
}
$human = People::getByLogin($login);
/...
class People extends EntityRepository
{
/**
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
*/
public $id;
/**
* @ORM\Column(type="string")
*/
public $login;
public static function getByLogin($login) {
$human = //???
return $human;
}
}
Answer the question
In order to leave comments, you need to log in
The People class itself should not inherit from EntityRepository. The repository is a separate class, in which such a method should be created, this is a good practice.
And then it’s better to make a service that will use the created repository, and the controller remains
class DefaultController extends Controller {
public function showAction($login)
{
$human = $this->get("PeopleService")->getByLogin($login);
}
}
You, apparently, absolutely do not understand the essence of Data Mapper , which is used in Doctrine . Entities don't need to know anything about the database at all. Somewhere you saw work with Active Record and decided that you need to drag the same approach here. It is not right. Here you need to use repositories to get data.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question