0

Complex PHP apps have hundreds of services. Every service is associated with a service identifier, usually it is a string chosen by developer. For example, repository.users.sqlite is an instance of UserRepository class configured to work with users table, default sqlite instance.

What is the proper naming convention for such a string?

I want to avoid unnecessary typing, thinking, CR debates, copy/pasting the service name and searching the codebase to find out what sits behind the identifier.

I see some options, however none is perfect:

  • use a string (something like repository.users.sqlite) and copy/paste it everywhere
$di['users.service'] = new UsersService($di['repository.users.sqlite']);
  • create a constant to hold service identifier somewhere in service provider class and use it:
const USERS_REPOSITORY_SQLLITE = 'repository.users.sqlite'; 
const USERS_SERVICE = 'users.service';

$di[self::USERS_SERVICE] = new UsersService($di[self::USERS_REPOSITORY_SQLITE]);
  • use built-in PHP class constants (UserRepository::class) as a naming approach for service identifiers. So, there is no need to create a constant or memorize something. Also, IDE's code completion works in this case.
$di[UsersService::class] = new UsersService($di[UsersRepository::class]); // default sqlite implementation is used here

What name convention for DI service identifiers do you use, and why?

Community
  • 1
  • 1
Vasily
  • 981
  • 10
  • 12
  • use built-in PHP class constants (UserRepository::class) not a best solution as if you rename a class - you have to update all the places throughout the app with a new name. You could look how this realized in symfony: you could use a configurable alias for the service. More is here: https://symfony.com/doc/current/components/dependency_injection.html – Ivan Ovcharenko Jun 12 '19 at 10:08

1 Answers1

0

If the frameworks does not force you to use string identifiers like Symphony does, I prefer to user ::class constant, cause:

  • Ready built-in constant. No need no think about identifiers names and values.
  • The class constant already contains all the information to identify the class: namespace, module and name.
  • Though the IDE is easier to find the usages of this class in container definitions.

For some exception where the same concrete service definition is repeated, I use as identifier: MyClass::name . '::customIdentifier';

BTW: I already worked with Symphony DI many years, but I still prefer this way I mentioned (Which i was currently using).