Services

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.

Declaration $components->service()Contract Service

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

bootstrap.php
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:

text
Application starting High: postgres
postgres is up.
Application starting Normal: Http

PostgreSQL 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 status alongside the other components — and counts it in call app health, the container’s health check: a database that is down makes it unhealthy.

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 require and one line in components().
  • Your own. A service is a plain class with two methods. How to write one is on the next page.

Next