Flag of Ukraine
SymfonyCasts stands united with the people of Ukraine

SELECTing into a New DTO Object

Keep on Learning!

If you liked what you've learned so far, dive in!
Subscribe to get access to this tutorial plus
video, code and script downloads.

Start your All-Access Pass
Buy just this tutorial for $6.00

With a Subscription, click any sentence in the script to jump to that part of the video!

Login Subscribe

Having the flexibility to select any data we want is awesome. Dealing with the associative array that we get back is... less awesome! I like to work with objects whenever possible. Fortunately, Doctrine gives us a simple way to improve this situation: we query for the data we want... but tell it to give us an object.

Creating the DTO

First, we need to create a new class that will hold the data from our query. I'll make a new directory called src/Model/... but it could be called anything. Call the class... how about CategoryFortuneStats.

The entire purpose of this class is to hold the data from this specific query. So add a public function __construct() with a few public properties for simplicity: public int $fortunesPrinted, public float $fortunesAverage, and public string $categoryName.

... lines 1 - 4
class CategoryFortuneStats
public function __construct(
public int $fortunesPrinted,
public float $fortunesAverage,
public string $categoryName,


Back in the repository, we actually don't need any Doctrine magic to use this new class. We could query for the associative array, then return new CategoryFortuneStats() and pass each key into it.

That's a great option, dead simple and then this repository method would return an object instead of an array. But... Doctrine makes this even easier thanks to a little-known feature.

Add a new ->select() that will contain all of these selects in one. Also add a sprintf(): you'll see why in a minute. Inside, check this out! Say NEW %s() then pass CategoryFortuneStats::class for that placeholder. Basically, we're saying NEW App\Model\CategoryFortuneStats()... I just wanted to avoid typing that long class name.

Inside of NEW, grab each of the 3 things that we want to select and paste them, as if we're passing them directly as the first, second and third arguments to our new class's constructor.

... lines 1 - 18
class FortuneCookieRepository extends ServiceEntityRepository
... lines 21 - 25
public function countNumberPrintedForCategory(Category $category): array
$result = $this->createQueryBuilder('fortuneCookie')
'NEW %s(
SUM(fortuneCookie.numberPrinted) AS fortunesPrinted,
AVG(fortuneCookie.numberPrinted) fortunesAverage,
... lines 37 - 44
... lines 46 - 88

Isn't that cool? Let's dd($result) so we can see what it looks like!

No Aliasing with NEW

If we head over and refresh... oh... I get an error: T_CLOSE_PARENTHESIS, got 'AS'. When we select data into an object, aliasing is no longer needed... or allowed. And it makes sense: Doctrine will pass whatever this is to the first argument of our constructor, this to the second argument, and this to the third. Since aliases don't make sense anymore... remove them.

... lines 1 - 25
public function countNumberPrintedForCategory(Category $category): array
$result = $this->createQueryBuilder('fortuneCookie')
'NEW %s(
... lines 37 - 44
... lines 46 - 90

If we check it now... got it! I love it! We have an object with our data inside!

Let's celebrate by cleaning up our method. Instead of an array, we're returning a CategoryFortuneStats. Also remove the dd($result) down here.

... lines 1 - 25
public function countNumberPrintedForCategory(Category $category): CategoryFortuneStats
... lines 28 - 43
... lines 45 - 89

Back in the controller, to show off how nice this is, change $result to... how about $stats. Then we can use $stats->fortunesPrinted, $stats->fortunesAverage, and $stats->categoryName.

... lines 1 - 12
class FortuneController extends AbstractController
... lines 15 - 30
public function showCategory(int $id, CategoryRepository $categoryRepository, FortuneCookieRepository $fortuneCookieRepository): Response
... lines 33 - 36
$stats = $fortuneCookieRepository->countNumberPrintedForCategory($category);
... line 38
return $this->render('fortune/showCategory.html.twig',[
'category' => $category,
'fortunesPrinted' => $stats->fortunesPrinted,
'fortunesAverage' => $stats->fortunesAverage,
'categoryName' => $stats->categoryName,

Now that we've tidied up a bit, let's check to see if this still works. And... it does.

Next: Sometimes queries are so complex... the best option is just to write the darn thing in raw, native SQL. Let's talk about how to do that.

Leave a comment!

Login or Register to join the conversation


This is the reason why I keep doing almost every SymfonyCasts tutorials. Even though I'm very familiar with Doctrine, I did not know that trick! It made my day!

Keep it up, friends!

Sidi-LEKHAIFA Avatar
Sidi-LEKHAIFA Avatar Sidi-LEKHAIFA | posted 4 days ago

It's really great this way, do you know if it only works if the DTO hydrates through the constructor or if the DTO can hydrate through the getters and setters?



That's a good question. I believe Doctrine does not support setter methods. They are not explicit about it in the docs though https://www.doctrine-project.org/projects/doctrine-orm/en/latest/reference/dql-doctrine-query-language.html#new-operator-syntax
I'd just give it a try to confirm it


1 Reply
Sidi-LEKHAIFA Avatar
Sidi-LEKHAIFA Avatar Sidi-LEKHAIFA | MolloKhan | posted 4 days ago | edited

Thanks @MolloKhan for your answer, yes I confirm that it doesn't work with setters, I just tried it. but it's good to know

1 Reply
Cat in space

"Houston: no signs of life"
Start the conversation!

What PHP libraries does this tutorial use?

// composer.json
    "require": {
        "php": ">=8.1",
        "ext-ctype": "*",
        "ext-iconv": "*",
        "beberlei/doctrineextensions": "^1.3", // v1.3.0
        "doctrine/doctrine-bundle": "^2.7", // 2.9.1
        "doctrine/doctrine-migrations-bundle": "^3.2", // 3.2.2
        "doctrine/orm": "^2.13", // 2.15.1
        "symfony/asset": "6.2.*", // v6.2.7
        "symfony/console": "6.2.*", // v6.2.10
        "symfony/dotenv": "6.2.*", // v6.2.8
        "symfony/flex": "^2", // v2.2.5
        "symfony/framework-bundle": "6.2.*", // v6.2.10
        "symfony/proxy-manager-bridge": "6.2.*", // v6.2.7
        "symfony/runtime": "6.2.*", // v6.2.8
        "symfony/twig-bundle": "6.2.*", // v6.2.7
        "symfony/webpack-encore-bundle": "^1.16", // v1.16.1
        "symfony/yaml": "6.2.*" // v6.2.10
    "require-dev": {
        "doctrine/doctrine-fixtures-bundle": "^3.4", // 3.4.4
        "symfony/maker-bundle": "^1.47", // v1.48.0
        "symfony/stopwatch": "6.2.*", // v6.2.7
        "symfony/web-profiler-bundle": "6.2.*", // v6.2.10
        "zenstruck/foundry": "^1.22" // v1.32.0