Search code examples
phpcakephpguzzlecakephp-2.x

Using guzzle with CakePHP 2.x


I am trying to use guzzle 6.x on a CakePHP 2.x application.

What I need to do is to initialize Guzzle Client to some of my controllers but on the controllers that it will be loaded I need it to be loaded with the same configuration.

Basically what I don't know is which is the best approach to implement it. I was thinking about the following:

  1. Shall I create a function in AppController that will create and return a Guzzle object and then save it to a protected property inside AppController? Maybe a function like setUpGuzzle() and call this function on the Controllers I need to load Guzzle Client.
  2. Shall I create a component and then load Guzzle Client to a public property of this component. Then I could use it like this $this->HttpClient->client->post()
  3. Shall I create a component and write one function for each of Guzzle public function? So I will have something like this $this->HttpClient->post().
  4. Thing is I don't like any of the above and I was hopping maybe there could be another way to do this. For example create a components which loads the Guzzle Client in a controller or loads the Guzzle Client inside the component collection.

Solution

  • Do you really need Guzzle? I agree that the old Cake2 HTTP socket is old fashioned but is there something it can't do that requires you to add yet another lib?

    Use a trait, as long as you're not stuck to an ancient php version this is a clean solution. Here is some pseudo-code that will give you the high level idea:

    trait HttpSocket {
        protected $_httpSocket = null;
        protected $_httpSocketConfig = [
            // Default config goes here
        ];
        public function getHttpSocket() {
            if (empty($this->_httpSocket)) {
                // Not sure how the constructur works, so it's just an example
                $this->_httpSocket = new Guzzle($this->_httpSocketConfig);
            }
            return $this->_httpSocket;
        }
    }
    

    If you ever need to change the config or the whole socket implement ion you just have to change it in a single place without the overhead of a component. Also this can be use in any class, not just controllers. What you're looking for is more or less a simple factory like method, no need for a whole controller.

    If you can't use a trait then you'll have to use a component or just put the above code not inside a trait nor a component but directly inside your AppController, but you won't be able to use it outside the scope of the controllers that inherit that controller then.