Services
A service is a program the application cannot work without: a database, a cache, a file server. You declare it in one line, and the application starts it, waits until it is ready and looks after it.
What a service is and why
What it is. A program that runs next to your code, in the same container. For example, the PostgreSQL your repositories talk to.
The problem. Such a program needs looking after:
- start it before HTTP — otherwise the first requests arrive while there is no database yet;
- restart it when it crashes or hangs;
- stop it last, once HTTP takes no more requests.
Writing this by hand in every project takes time, and it is easy to get wrong.
The solution. A service knows how to start and check its program itself. All that is left to you is to tell the application: “I need this service”.
What it looks like
use Flytachi\Winter\Service\Postgres\Postgres;
protected static function components(Components $components): void
{
$components->service(new Postgres(database: 'app'));
}When the application starts, the log says:
Application starting High: postgres
postgres is up.
Application starting Normal: HttpPostgreSQL came up first, and HTTP only once it answered.
What the application does with a service
- Starts it before the rest and waits until it is ready.
- Checks that it is alive: one that crashed or hung is restarted.
- Stops it last, after HTTP and the processes.
- Shows it in
call application statusalongside the other components — and counts it incall app health, the container’s health check: a database that is down makes itunhealthy.
A service is a component like HTTP or a process — only described in advance and packed into a class.
Where services come from
- Ready-made packages: PostgreSQL,
MariaDB, Redis —
composer requireand one line incomponents(). - Your own. A service is a plain class with two methods. How to write one is on the next page.
Next
- Your own service — a simple service from scratch.
- What the image needs — when the program is not in the image.
- PostgreSQL, MariaDB, Redis — ready-made packages.