Dependency Injection is some of the bigger buzzwords in PHP frameworks.
Historically, CakePHP application logic didn’t support that, until the version 4.2 was released last December. You can do that on your own and have a few plugins for that.
This is a new chapter of the framework, let's see how to bake it.
Use Case
First, let’s talk about a classic Use case on real applications.
Our application will include an address form, such as the shipping address for an online order, or provide information about User, Company, etc. Autocomplete can help users supply the details.
We will use the Geocoding API from Google Maps Platform, making a HTTP request for API with json output format and address parameter:
https://maps.googleapis.com/maps/api/geocode/json?address=89104&key=******
And here we go, we will get this result:
Baking a Address Service
After seeing the Use case, all we need on our backend is to make a HTTP request for API and return the JSON result for the frontend to populate related fields.
1. First, let’s exposing our application for accept “.json” requests:
2. Now, we can bake a Address Controller and let’s request an empty result:
$ ./bin/cake bake controller Address --actions index
Now our app requests /address.json will return an empty JSON.
3. Let’s bake (manually) the Address Service:
Basically I’m using Cake\Http\Client to make the API request. Also I read Geocode.key from Cake\Core\Configure, we don't want to expose our key on public requests (add the key on config/boostrap.php).
4. Let’s rewrite our Controller:
5. Finally, let’s add our Service on Application.php:
That’s all bakers! Now our endpoint /address.json will support query parameters and return the result of the API request.
The cost of shiny
I’m here selling an idea and I don't start with the cons. Unfortunately, the Dependency Injection container is an experimental feature that is not API stable yet.
The support is a bit limited, CakePHP will inject services into: constructors of Controllers and Commands and Controller actions.
The core team hopefully stabilizes the feature on version 4.3, or at most 4.4. They need your help testing and finding cases, and feedback always is welcome.
I hope this post can be useful for you and your projects. See you next time!