What is the best way to get the 'Request' object in the controller?

前端 未结 2 1696
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-03 22:55

I have seen the request object being passed to the controller action method as a parameter like this:

public function addAddressAction(Request $request)
{
           


        
相关标签:
2条回答
  • 2021-01-03 23:17

    As far as I know there's no difference. It doesn't interrupt affect much either way. Even if you want to specify required parameters in your action. E.g.

    /**
     * @Route("/edit/{id}", name="edit")
     */
    public function editAction(Request $request, $id)
    {
        // Both $request and $id are available
    }
    
    0 讨论(0)
  • 2021-01-03 23:32

    If you take a deeper look at the Symfony2 Base Controller code, you may notice that getRequest() is marked as deprecated since version 2.4 and will be removed in 3.0.

    /*
     * ...
     * @deprecated Deprecated since version 2.4, to be removed in 3.0. Ask
     *             Symfony to inject the Request object into your controller
     *             method instead by type hinting it in the method's signature.
     */
    public function getRequest()
    {
        return $this->container->get('request_stack')->getCurrentRequest();
    }
    

    Introduced by the following evolution,

    • [FrameworkBundle] use the new request_stack service to get the Request object in the base Controller class.

    And, here's the upgrade from 2.x to 3.0 documentation.

    • Upgrade from 2.x to 3.0 - FrameworkBundle

    Conclusion,

    Your Request should then be part of your action's signature.

    0 讨论(0)
提交回复
热议问题