Viliam Jobko
Viliam Jobko

Reputation: 335

Symfony2: Using renderView method in new Controller

I got two Controllers:

class FirstController extends Controller
{
    /**
     * @Route("/first")
     */
    public function indexAction()
    {
        $second = new SecondController();
        $second->doit();
    }
}


class SecondController extends Controller
{
    public function doit()
    {
        $render = $this->renderView('::base.html.twig');
        //write $render to disk
    }
}

Instead of 'done' being written to my screen, I got error: Error: Call to a member functuin get() on null

What am I doing wrong?

Upvotes: 1

Views: 278

Answers (1)

greg0ire
greg0ire

Reputation: 23255

You are not supposed to instantiate controllers yourself. The framework is supposed to do that for you. If you are in controller1, and want controller2 to actually handle the request, which could use some explanation on your part, you need to forward to it, like this : $this->forward('MyBundle:MyController:myaction)

Also, you should maybe have your doit method in a service. Controllers are supposed to stay skinny, and care only about HTTP:

  • they receive the request
  • they call a service based on the request, this service should know nothing about HTTP, and be callable from a command as well as from a controller
  • they return a response based on what the service answers.

Upvotes: 2

Related Questions