insertusernamehere
insertusernamehere

Reputation: 23580

Symfony2 - EntityRepository - Sorting rows - is this a good and save approach?

Doctrine created a repository for my class and to get a list of all elements sorted by any row, I wrote this member:

class NoteRepository extends EntityRepository {
    public function findAllOrderedByRow($row, $order = 'ASC') {
        if ( 'DESC' != strtoupper($order) ) {
            $order  = 'ASC';
        }

        if ( property_exists('Namespace\Entity', $row) ) {
            return $this->getEntityManager()
                ->createQuery('SELECT o FROM Entity o ORDER BY o. ' . $row . ' ' . $order)
                ->getResult();
        }

        return null;
    }
}

My question is, whether this is a good approach or is it better to add functions for all rows that are sortable? And is it save, to use it like that? I don't see a way for an injection. But maybe I overlooked it.

Many thanks, Philipp

Upvotes: 1

Views: 3694

Answers (1)

i.am.michiel
i.am.michiel

Reputation: 10404

There is a function available in the EntityRepository called findBy. You can pass the order by as second parameter.

public function findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)

And a little example :

$this->getDoctrine()->getRepository('User')->findBy(
    array(), 
    array('email' => 'asc')
);

Overriding this behaviour is in my point of view useless.

Upvotes: 4

Related Questions