Search code examples
phpsymfonysonata

getPublicUrls() returns an empty array


I have a repository of Media objects in my Symfony app that contains a picture. (This picture was uploaded using the Sonata Media Bundle.) Using the following code in my controller ...

    $images = $repository->findAll();

    foreach ($images as $image) {
        /* @var $image Media */
        $urls = $image->getPublicUrls();
        $output[] = [
            'name' => $image->getName(),
            'something' => $urls,
        ];
    }

... results in an empty array where I had hoped to see at least one public-facing url.

What have I misconfigured?


Solution

  • I ended up doing the following:

        $images = $repository->findAll();
    
        /* @var $imageProvider ImageProvider */
        $imageProvider = $this->get('sonata.media.provider.image');
    
        foreach ($images as $image) {
            /* @var $image Media */
            $output[] = [
                'name' => $image->getName(),
                'url' => $imageProvider->generatePublicUrl($image, 'reference'), 
            ];
        }
    

    This doesn't really answer my original question, but it achieves the goal that I was going for, in that it provides a publicly accessible url for my image.