This is done in the file, where “example” is the name of your module. The only mandatory aspect of creating a service is telling Drupal how to instantiate it. The custom service class doesn't need to extend any other class. You can create your own services by either creating a class that encapsulates the functionality needed or telling Drupal how to instantiate it from the service container. module file (a function that’s not a hook), consider doing it as a service, since that’s probably how it should be done. If you’re writing a helper or reusable function in your. For example, if you have a controller with a helper function and you realize you can use this helper function in another controller (or another class), you should move this function to a service and inject it into the classes that need it. Almost everything we do in Drupal is tied to a service: for example, knowing the current user of the site \Drupal::currentUser(), the current path \Drupal::routeMatch(), accessing and altering nodes and other entities, generating UUIDs, managing path aliases, and so on.ĭrupal provides many services in core, but we can also create our own custom services. They are classes used to encapsulate a specific functionality. In Drupal, services are objects living inside the service container. ![]() For every Drupal component, the namespace will always start with \Drupal and the rest will depend on what type of element we're adding the class to, following the pattern described in the official documentation. The namespaces work for package-based autoloading and use the standard PSR-4. In Drupal, every class you create must have a corresponding namespace. Probably the most common trait in Drupal is the StringTranslationTrait, which enables the use of the “t” function to translate strings. Traits - An alternative for reusing code, they allow classes that use them to access certain functions without duplicating the code.They define what methods and properties the class should have. Interfaces - These are base templates implemented by classes. ![]() Each class can have use statements at the top and requires other classes, interfaces or traits to provide the service.
0 Comments
Leave a Reply. |