This mini-tutorial shows how to use the Packagist API to display downloads and stargazers of a package.
Lately, we were working on our landing page for TNT Analytics, and we wanted to show those numbers on the landing page.
Github is providing an API, but in order to use it, you need to have a token. That's why we decided to use the API from packagist, which, together with downloads, also includes the number of stargazers for a package.
The first question that comes to mind to a junior developer might be:
Where to put this piece of code
If you are in a hurry, you'll probably put the code inside a controller. But as everybody knows, controllers should have only one responsibility, or sometimes if there's no other way around, as little as possible.
This kind of code could be considered as business logic. In our example, we added caching to it, but you might do some other stuff related only to your business. So we decided to treat it as a service class. Service classes would go into the app\Services
directory, just like the name suggests.
Notice that we're here using Laravel's cache because we don't want to hit the API on every page refresh.
Now, we can call the code from a controller and pass the results to a view.
We could further refactor this and leverage the power of Laravels service container. The final result would look like this:
The controller is lean and passes the required data to the view. This might be a simple use case, but it has a much bigger effect on your development praxis. If you keep spliting your code this way, you'll code gets easier to maintain and will be reusable.
Start small and you'll save yourself a lot of trouble when the codebase grows!