phpsymfonycommand-line-interfacesymfony-2.6

how to use class controller functions in command class of symfony 2?


I am building a batch file using symfony 2 command class. I have a function which deals with DB from a controller inside a bundle

class SubmitDisclosureController extends FOSRestController implements MEAuthController { ... public function discDetails($discId) {
$emr = $this->getDoctrine()->getEntityManager();

I am calling this from a command src/AppBundle/Command/BatchJobCommand.php which is as below

class BatchJobCommand extends Command
{
protected function execute(InputInterface $input, OutputInterface $output)
{
    $output->writeln([
            'User Creator',
            '============',
            '',
        ]);

    // retrieve the argument value using getArgument()
    $output->writeln('First batch job')

    $disc = new SubmitDisclosureController();
    $disc->discDetails('42094');
`

If I try to execute it, it gives PHP Fatal error: Call to a member function has() on null in C:\xampp\htdocs\GR\ vendor\symfony\symfony\src\Symfony\Bundle\FrameworkBundle\Controller\Controller. php on line 288

is it not possible to re-use the code by calling the functions of a controller from a command class?


Solution

  • What's saying Matei is exactly what you need : create a Service and use it on each class :

    class DisclosureService { ...  public function discDetails($discId) {...}  }
    

    In your services.yml configuration file, you have to add it.

     disclosure:
        class:  Your\Namespace\DisclosureService 
        arguments: ["@doctrine", ...]
    

    In your command & controller, you can call the service with :

    $this->get('disclosure')->discDetails('')
    

    Details can be found on the official doc : http://symfony.com/doc/current/service_container.html