S
S
suzyry2016-06-01 14:52:29
symfony
suzyry, 2016-06-01 14:52:29

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]);
    }
}

Question: How could such operations (on working with the database) be reduced to certain methods.
For example:
$human = People::getByLogin($login);
There is a class in AppBundle/Entity/People that inherits EntityRepository.
/...
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;
    }
}

Thank you very much for your attention!

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexey Pavlov, 2016-06-01
@lexxpavlov

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

A
Alexey Skobkin, 2016-06-01
@skobkin

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 question

Ask a Question

731 491 924 answers to any question