Giuseppe, I recommend defining your service using the Factory design pattern. You can then instance the factory and call a copy of your business logic class, initialized with the nid. I believe that this pattern is what @kiamlaluno was hinting at in his comment about using DatabaseBackendFactory.
Factory injection example
A simple and common example of this pattern would be getting an instance of a storage controller from the EntityTypeManager.
In your .services.yml file:
example_service:
class: Drupal\my_module\MyExampleClass
arguments: ['@entity_type.manager']
In your service class:
<?php
use Drupal\Core\Entity\EntityTypeManagerInterface;
class MyExampleClass {
/**
* @var \Drupal\Core\Entity\EntityStorageInterface
*/
protected $termStorage;
/**
* @inheritDoc
*/
public function __construct(EntityTypeManagerInterface $entity_type_manager) {
$this->termStorage = $entity_type_manager->getStorage('taxonomy_term');
}
}
In the example above, the EntityTypeManager, which acts as a factory, has been injected, and then we call the getStorage()
method to get an instance of \Drupal\Core\Entity\EntityStorageInterface
that has been initialized for the taxonomy_term entity type.
Similarly, you could define a service that is, itself, a factory, and the factory would then be responsible for creating instances of your business logic class.
You could inject your factory service, as in the example above, by replacing the EntityTypeManager service with your own. You can also create an instance in a hook, like this:
my_module_node_view($node, $view_mode, $langcode) {
// Get instance of your factory service.
$my_service = \Drupal::service('my_service');
// Get an instance of your business logic class from the factory,
// initialized to use the nid that we provided from $node->id().
$node_processor = $my_service->get($node->id());
// Make the call to process the nid.
$node_process->doBusinessLogic();
}
Plugins
It might also be helpful to know about Drupal 8's plugin system. Drupal 8's plugin system is essentially a specialized version of the factory pattern. If you have Drupal Console, then generating new Annotation plugins is easy. Depending on all of the requirements of your project, a custom plugin type might be exactly what you need.
Here are some tutorials and references on plugins that I have found to be useful:
DatabaseBackendFactory
, you should still call a method to set that property.