Manojkumar
Manojkumar

Reputation: 1359

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?

Upvotes: 0

Views: 1724

Answers (2)

Yoann
Yoann

Reputation: 76

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

Upvotes: 1

Cerad
Cerad

Reputation: 48865

$disc = new SubmitDisclosureController();
$disc->setContainer($this->getContainer());
$disc->discDetails('42094');

Will get you past the error message. However, as @MateiMihai says, a better design would be to move the disc functionality into it's own service and then share it between your controller, command and testing classes. http://symfony.com/doc/current/service_container.html `

Upvotes: 3

Related Questions