简体   繁体   中英

In Symfony 2, what is the best way to make a function available to all repository classes

I often find I want to get a simple array of ids from a query. The way I do this at the moment is to use this code

$queryBuilder = $this->createQueryBuilder('s')
        ->select('s.id');

$result = $queryBuilder->getQuery()->getArrayResult();

// flatten the array
$ids = array();
array_walk_recursive($result, function ($a) use (&$ids) {$ids[] = $a;});

return $ids;

I don't find the syntax easy to remember so I'd like to create a function that all repository classes have access to, allowing me to do something like this

$queryBuilder = $this->createQueryBuilder('s')
    ->select('s.id');

return $this->getArrayIds($queryBuilder->getQuery()->getArrayResult());

I was thinking of using a service class, but that seems like it would go against some design patterns as I'd have to inject a service container or something into all the repository classes.

What would be the best way to do this?

edit:

In case any one is interested, here is the class I created based on the accepted answer

<?php
namespace MyApp\MyBundle\ORM;

use Doctrine\ORM\EntityRepository as BaseEntityRepository;

class EntityRepository extends BaseEntityRepository
{
    /**
     * Flatten a QueryBuilder array of entity ids
     *
     * @param array $queryArray
     *
     * @return array | false
     */
    public function getQueryIds($queryArray)
    {
        $ids = array();

        if (array_walk_recursive($queryArray, function ($a) use (&$ids) {$ids[] = $a;})) {
            return $ids;
        } else {
            return false;
        }
    }
}

I think that you could extend Doctrine\\ORM\\EntityRepository class which is default repository class in Doctrine.

namespace Your\Namespace;

use Doctrine\ORM\EntityRepository;

class MyEntityRepositoryClass extends EntityRepository {

    public function yourMethod() {
        // ... build query, execute, process etc.
    }

}

Then configure Doctrine to usethis class as default repository class by setting default_repository_class option to My\\Namespace\\MyEntityRepository

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM