Symfony logo

Read Json in Symfony 5 controller from asset directory

We all know Symfony is awesome. Recently for some project which is in initial stages I had to read some JSON data from a file which i placed in asset/json directory. I knew about previous versions but in latest symfony I was facing problem.

Googling took me to some stackoverflow pages and it actually almost get me to solution. The catch was however slightly different than what I was expecting.

So as we all know in symfony 5 we have autowiring feature, which allows you to pass a service directly to controller as parameter passing. So I took the Idea from Stack overflow and passed the package.

    /**
     * @Route("/test")
     * */
    public function test(Symfony\Component\Asset\Packages $packages){
       $path = $packages->getUrl('assets/json/test.json');        
       $data = file_get_content($path);
       return new Response('OK'); 
    }

So I was expecting it to work, but ‘uh oh..’ error, file not found. So I dig in the symfony documentation and found out there is slight difference in how it would work. The package we needed wasn’t available as service but I needed to create an object of Package and not Packages.

/**
 * @Route("/readjson/test")
 * */
public function readJsonTest(){
    $package = new Symfony\Component\Asset\Package(new EmptyVersionStrategy());
    $path = $package->getUrl('assets/json/test.json');
    $data = file_get_contents($path);
    $jsonData = json_decode($data,1);
    print_r($jsonData);
}

This worked for me, while my assets directory was lying in public directory. Now both Package and Packaged are placed together but autowiring doesn’t work with it.

While I shared my solution in hope that somebody will find it helpful, I would like if any of the readers can explain why original solution doesn’t work.

Leave a Comment

Your email address will not be published.