Symfony2 - How to perform an external Request

后端 未结 6 1645
走了就别回头了
走了就别回头了 2020-12-14 01:48

Using Symfony2, I need to access an external API based on HTTPS.

How can I call an external URI and manage the response to \"play\" with it. For example, to render a

6条回答
  •  [愿得一人]
    2020-12-14 01:50

    Symfony doesn't have a built-in service for this, but this is a perfect opportunity to create your own, using the dependency injection framework. What you can do here is write a service to manage the external call. Let's call the service "http".

    First, write a class with a performRequest() method:

    namespace MyBundle\Service;
    
    class Http
    {    
        public function performRequest($siteUrl)
        {
            // Code to make the external request goes here
            // ...probably using cUrl
        }
    }
    

    Register it as a service in app/config/config.yml:

    services:
        http:
            class: MyBundle\Service\Http
    

    Now your controller has access to a service called "http". Symfony manages a single instance of this class in the "container", and you can access it via $this->get("http"):

    class MyController
    {
        $response = $this->get("http")->performRequest("www.something.com");
    
        ...
    }
    

提交回复
热议问题