Search code examples
phpsymfonysymfony-2.8

Write automatically in services.yml file


I want to create a php class that writes automatically a service in the services.yml file based on my entities ( on server run or with a command ) .Is it possible to do so or should I just use the filesystem to do it ?


Solution

  • You can but the newly created service will be unavailable until the next request.

    To retrieve the services.yml of a bundle :

    // src/AcmeBundle/Controller/DefaultController.php
    
    $kernel = $this->get('kernel');
    $servicesPath = $kernel->locateResource('@AcmeBundle/Resources/config/services.yml');`
    

    Or the global services.yml of your application :

    $servicesPath = $kernel->getRootDir().'/config/services.yml';``
    

    Write your new service into :

    $parser = new \Symfony\Component\Yaml\Parser();
    $dumper = nrw \Symfony\Component\Yaml\Dumper();
    
    // Get the services already configured, use the path of 'services.yml' retrieved from bundle/application
    $oldServices = $parser->parse($servicesPath); 
    $newService = array('your_service_name' => array( 
       // Here your arguments, tags, ...
    );
    
    $mergedServices = array_merge($oldServices, $newService);
    $yamlServices = $dumper->dump($mergedServices);
    
    // Write all in the configuration file
    file_put_contents($servicesPath, $yamlServices); // $services is the 'services.yml' path