Sonata Media another great bundle that we get from Sonata-Project family. Sonata Media is a bundle for media management and like any other bundles from Sonata-Project, documentation sucks. Maybe you are transferring some old project to Symfony or you decided that Sonata Media is something you need and you have some images attached, in my case, it was a lot of images. I will explain how I dealt with this problem and what was the best way I found to solve it.

Upload Image Programmatically

This will be a simple example of how to save image as Media Object.

$item; //Entity where you added Sonata Media field
$mediaManager = $this->get("");
$media = new \Application\Sonata\MediaBundle\Entity\Media();

$media->setContext('default'); //contex you are using

//call entity manager and save object

So now you created Media Object and saved to your new Entity.

Migrating Images and Galleries

Here is the code I used to migrate everything and I thought it would be cleaner if you just look at gist.

I created a Symfony Command that I registered as service and passed sonata managers and upload directory, also to avoid command timeout I:

You can increase flush to more than 10 iterations but in my example, I created Sonata Media Galleries with 10+ images. This script took longer time because of precautions I took but after 5000 images there was no timeout, it was worth it.

If you are stuck at line 102, maybe you can create Entities from old database tables and then get all galleries or images, maybe you can create additional connection and import that database as another bundle, where you would call separate entity manager connection for every database and then grab images from old database.

I just checked gist and I see the code is not up to PHP Coding Style Standards also I see a lot of space for refactoring but I am currently out of time to change that and I encourage you to read about PSRs and follow Standards.

Hope this helps someone and if you are stuck somewhere with this, feel free to email me for help.