简体   繁体   中英

Extend controller - but how activate it? (Symfony 2)

I want to use this code in my application:

class ControllerExtension extends Symfony\Bundle\FrameworkBundle\Controller\Controller 
{
    public function render($view, array $parameters = array(), Response $response = null)
    {

        //etc.

    }

}

But where do I put it and how do i activate it? I'm guessing it's something to do with the services.yml file. I've used Event Listeners, but this is obviously different.

From your code snippet ( http://justpaste.it/2caz ), it seems that you missed the "return" keyword in your call to parent.

class ControllerExtension extends Symfony\Bundle\FrameworkBundle\Controller\Controller 
{
    public function render($view, array $parameters = array(), Response $response = null)
    {
        if($this->getRequest()->getRequestFormat() == 'json') {
            return new Response(json_encode($parameters));
        } else {
            // Missing 'return' in your snippet
            return parent::render($view, $parameters, $response);
        }
    }

}

class MyController extends ControllerExtension
{
    public function indexAction()
    {
        // This should now work
        return $this->render(...);
    }
}

You can put it in your bundle's Controller directory ie src/YourNamespace/YourBundleName/Controller/ControllerExtension.php . Make sure you provide the appropriate namespace in that file:

namespace YourNamespace\YourBundleName\Controller;
class ControllerExtension extends Symfony\Bundle\FrameworkBundle\Controller\Controller
{
...

To use it, either create a route for it in src/YourNamespace/YourBundlename/Resources/config/routing.yml

or

extend it:

namespace YourNamespace\YourBundleName\Controller;
class OtherController extends ControllerExtension
{
...

If what you are actually looking to do is override another bundle's controller, see the cookbook which describes overriding controllers .

Edit :

As far as I know, there's no way to automatically make this controller somehow take effect. You can have each of your controllers extend it as I've indicated above.

You might be able to create an event listener and use the response event to somehow change the response if the format is json. But, I'm not sure how you would access the view data from the event listener.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM