Pergunta

I have recently started working with Doctrine ORM and I am struggling with the holistic idea of how to get an array of information from a database.

Typically I would do something like this:

$sql = "SELECT * FROM Users";
$userArray = $this->db->fetchAll($sql);

I am able to use setters and getters to update information using my Entity... I have absolutely no clue how to go about using entites to grab information from the DB...

This is what I have:

Controller:

   public function usersAction() {
   $userFunctions = new UserFunction;
   $userArray = $userFunctions->getUsers();
   $viewModel = new ViewModel(array('users' => $userArray));
   return $viewModel;

UserFunction:

<?php

namespace Administration\Model;

use Doctrine\ORM\EntityManagerInterface;
use Zend\Paginator\Paginator;
use Zend\ServiceManager\ServiceManager;

class UserFunction
{
protected $entityManager;
protected $em;

function __constructor(EntityManagerInterface $entityManager) {
    $this->em = $entityManager;
}

public function getUsers()
{
    //Do some DB fetching magic and return user list in an array
    return array(1,2,3,4,5);
}

}

If you can suggest the HOW to fetch the DATA using ORM Doctrine, that would be much appreciated.

Foi útil?

Solução

Your data will be returned as an array of entities:

Your "getUsers()" method might look like this:

/**
 * Returns an array of User entities.
 */
public function getUsers()
{
    return $this->em->getRepository('My\Entity\User')->findAll();
}

The method returns an array of objects (specifically, objects of class \My\Entity\User).

In your view script, you might do something like:

<h1>All Users</h1>
<?php foreach($users as $u): ?>
<?= $u->getUsername(); ?><br/>
<?php endforeach; ?>

So, when you ask about "go about using entites to grab information from the DB...", what you really want to do is "use the EntityManager (and/or EntityRepositories) to grab entities from the DB".

Remember: Entities themselves don't know about persistence (the DB). But the EntityManager and Repositories do.

Finally, based on this question, and another of yours I answered, I suggest you take a look at Repositories in Doctrine. You seem to be reinventing that wheel to some degree.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top