Questions tagged [dependency-injection]

Use it for questions about implementing the software design pattern that implements inversion of control.

Filter by
Sorted by
Tagged with
16
votes
3answers
5k views

"Drupal calls should be avoided in classes, use dependency injection instead"

In my module using below code for getting url alias of given url: $alias = \Drupal::service('path.alias_manager')->getPathByAlias($_POST['url']); But one I run Automated Review(http://pareview.sh/...
15
votes
1answer
6k views

How do I use dependency injection on \Drupal::moduleHandler() to a Controller?

I am using the following line in a controller class. \Drupal::moduleHandler()->alter('mymodule_myfunction', $plugin_items); Pareview.sh is giving me this error message. \Drupal calls ...
12
votes
1answer
10k views

Correct way to call a service in a controller

I'm new to services (and drupal 8!) and trying to figure out services. I think perhaps I'm just doing the create in an outdated way. What I want do is make my 'hello generator' a service and call it ...
10
votes
1answer
1k views

Dependency Injection in Custom Field Widget

I am trying to inject the entity query service into a custom field widget. This is the relevant code: /** * Plugin implementation of the 'address_options' widget. * * @FieldWidget( * id = "...
9
votes
1answer
4k views

Dependency injection in a custom class

I have a custom module (my_module); Inside this module I have a custom class (MyClass), where I want to use a Drupal service (file_system). This is my code. src/MyClass.php namespace Drupal\...
8
votes
2answers
6k views

Dependency injection to load node data

When I checked the code I wrote with phpcs --standard=DrupalPractice /path/to/myController, I got the following warning. WARNING | Node::load calls should be avoided in classes, use dependency ...
8
votes
1answer
2k views

how to unit test an http client service with DI in drupal 8?

I have a service the consumes data from an external source. I would like to unit test the service and I am not sure how to get the test set up. To start with I would like to just test 1 method. Here ...
7
votes
2answers
2k views

What is public static function create() in plugins for?

Sometimes I encounter a public static function create() in plugin classes, for the example in the code show in Tutorial on Using Drupal 8 Plugin Derivatives Effectively. public static function create(...
7
votes
3answers
6k views

How to inject the database connection into a custom service?

I have a custom module that pulls data from several different external databases that have been defined as connections in settings.php. The current setup includes a series of controllers that have a ...
7
votes
1answer
2k views

How to inject a service in another service?

I am building a custom service, a membership service. This service can be called from a controller. But what I don't seem to get working, is to use another service, the QueryFactory, to use in that ...
6
votes
2answers
7k views

How to use dependency injection for Plugins/Blocks [\Drupal::formbuilder() and \Drupal::config()]?

I cannot get my head around this dependency injection theory. How are we supposed to get the below methods aligned with dependency injection? \Drupal::routeMatch()->getParameter('node'); \Drupal::...
6
votes
2answers
2k views

Dependency injection not working custom form

I have a custom module with a form class, where I am trying to inject a custom service to use within it's submit method: namespace Drupal\my_module\Form; use Drupal\Core\Form\FormBase; use Drupal\...
6
votes
2answers
2k views

How do I use the global class \Drupal static methods to access services?

Is there a difference between calling \Drupal::service('config.factory') and \Drupal::configFactory()? Is it better to use the second one? Can \Drupal be used to do something else than calling ...
6
votes
1answer
1k views

Why isn't my service found?

I'm trying to load a service into my Drupal module, but even after checking twice whether I did something wrong, I can't seem to find any error in my code as I did everything as the documentation said ...
5
votes
1answer
3k views

Problem with dependency injection (File::load and \Drupal::service)

In order to make a managed_file field permanent I did this in my module configuration form: <?php namespace Drupal\my_module\Form; use Drupal\Core\Form\ConfigFormBase; use Drupal\Core\Form\...
5
votes
1answer
335 views

What is the right way of loading a service?

when trying to use a service in drupal actually there is 3 ways , what is the preferred way to use a service and why : passing dependencies directly through the constructor: public function ...
5
votes
1answer
5k views

Dependency inject a class with values from a config object?

Is it possible to DI dependencies in Drupal 8 but initialize it with values from a config object? For example, SoapClient requires specifying the WSDL when called. I have different WSDL URLs ...
5
votes
1answer
2k views

Dependency Injection and the Url object

I'm making the leap from Drupal 7 to Drupal 8 and am still fuzzy on some core concepts, particularly relating to dependency injection (DI). I've read plenty of tutorials and have a grasp on DI with ...
5
votes
1answer
477 views

Can I get dependent services into a custom class without creating a service?

I've got a class hierarchy where I need to be able to instantiate different objects within the hierarchy. Instead of using global functions, I'd like to use injected services from the container via $...
4
votes
1answer
558 views

Difference between calling a service method in drupal 8

I want to know what difference does it make when i call a service this way : $service = \Drupal::service('myservice.method'); $service->methodNameInService(); or this way (Dependency Injecton) ...
4
votes
2answers
974 views

How do I instantiate a custom class with dependency injection?

I am relatively fresh to the DI party and am struggling to get my head around how exactly to use Dependency Injection. I understand that I can pass requirements as part of a service, but what about in ...
4
votes
1answer
399 views

How to inject a fake class into container when running WebTestBase tests?

I've got a form class, and I'm injecting my custom functionality class into it via constructor. That class is added to the container via the services.yml file defined in my custom module. I'd like to ...
3
votes
1answer
357 views

How can I inject a different service in an existing one, i.e. exchange one already injected service by an own one?

The basic authentication provider service uses the user.auth service: basic_auth.authentication.basic_auth: class: Drupal\basic_auth\Authentication\Provider\BasicAuth arguments: ['@config....
3
votes
0answers
537 views

How can I use TwigExtension from an existing symfony bundle?

UPDATED Context I'm using Symfony Webpack Encore to take care of all the JS and CSS postprocessing, transpiling and so on... There are different ways to implement webpack, even a module, Webpack ...
2
votes
1answer
2k views

How to call User::load with dependency injection

I have code that worked, but I wanted to clean it up and use dependency injection. I'm working in a BlockBase that implements ContainerFactoryPluginInterface. class DefaultBlock extends BlockBase ...
2
votes
2answers
2k views

Dependency Injection Syntax

I'm trying to build a simple module (to learn DI) to return the current user ID, and and apparently I'm missing something in the syntax. Here's my code and the error it's producing: use Drupal\Core\...
2
votes
1answer
1k views

Drupal 8 \Drupal calls should be avoided in classes, use | | dependency injection instead

I used Drupal 8 and written a module. in my form page I called. \Drupal::service('library.discovery')->clearCachedDefinitions(); $cache = \Drupal::cache('discovery'); $cache->delete('...
2
votes
2answers
173 views

Is it possible to define a FieldFormatter as a service

I need the 'language_manager' service inside a custom FieldFormatter. I'd prefer not to use \Drupal::service('language_manager'). Is there a special tag for FieldFormatters, or any other method to ...
2
votes
1answer
93 views

How to inject an object into a service?

I need to do a couple of things: Inject guzzle's httpclient into class A Inject class A into my service What I've tried so far: services: my_module.field_fetcher: class: Drupal\my_module\...
2
votes
2answers
71 views

What good is the create() method? [closed]

Most classes are instantiated using create($container) and __construct(...$services) in conjunction, it seems that the more efficient workflow would be to simply pass the container to the constructor ...
2
votes
1answer
520 views

How do I find services?

What is the best way to find right service for dependency injection? Googling is not efficient yet. For example I spent quite long time figuring out that if I need current request passed to ...
2
votes
1answer
1k views

how to inject dependencies into an access controller?

I am altering an existing route and adding a custom access. The custom access is a method that I want to have it in it's own access controller: /** * Alters existing routes. */ public ...
2
votes
1answer
3k views

How to pass argument in service with dependency injection

In a custom module, I have a custom service that uses GuzzleHttp\Client service. mymodule.services.yml: services: mymodule.mymodule_call: class: Drupal\mymodule\MyModuleCall arguments: ['@...
2
votes
1answer
45 views

How to solve this error "Class \Drupal\simple_sitemap\Controller\SimpleSitemapController does not exist"

I got this error which is kind of surprising to me since I don't have it on my local environment. What I did is that I compressed the project directory and uploaded it to my cpanel file manager and ...
2
votes
0answers
55 views

How do I mock a service when using BroswerTestBase? [duplicate]

I am trying to use BrowserTestBase to write a functional test for a Form. The form populates some form elements with data retrieved from an external site. The client for this external site is injected ...
2
votes
0answers
99 views

Design help for serialized classes that need database access

I want to convert from \Drupal::database() to dependency injection. I'm not 100% certain how to move forward with a refactor I know I have to complete. Currently I have a series of custom classes ...
1
vote
3answers
587 views

How to do dependency injection on complex classes like when extending WidgetBase

Since the Drupal sniffer whines at you if you call \Drupal::service() in your code, I have been trying to figure out how to use dependency injection on a widget I’ve been working on. Here’s what I’ve ...
1
vote
1answer
450 views

Dependency injection on module.install

How do I leverage dependency injection for drupal 8 when invoking my module.install->hook_install() mehtod? Or do I have to use \Drupal:: method at this point?
1
vote
1answer
256 views

How to check config setting in custom service class with dependency injection?

In a custom Service class, I need to check a config setting. I'm able to do this using \Drupal::config(static::SETTINGS) as documented here: https://www.drupal.org/docs/drupal-apis/configuration-api/...
1
vote
4answers
2k views

How can I get the form builder service using dependency injection?

How can I change form builder call in class in to dependency injection method? My current code: class CustomBlock extends BlockBase { /** * {@inheritdoc} */ public function build() { $...
1
vote
1answer
994 views

Dependency Injection while Unit Testing

Normally with Drupal 8 I can use dependency injection like this: <?php class ExampleController extends ControllerBase { private $http_client; public function __construct(HttpClient $...
1
vote
1answer
100 views

Return a Closure from a Factory

I have services that depend on request information. I'm trying to create a Factory Factory which will have the Dependency Injection container returns a factory (an anonymous function) that will create ...
1
vote
2answers
662 views

How do I inject UserInterface into Access Control?

I am trying to create a custom access control in my custom module in Drupal 8. But I am having issues in achieving it. I cant find a proper way to inject UserInterface class in access method. ...
1
vote
1answer
4k views

How to convert objects into array using serialization API?

I'm trying to convert entity objects into array but it's not working. Can you please help me spotting the mistake. I need to use `serializer.normalizer.content_entity' service. The code I have written ...
1
vote
1answer
64 views

Calling a Method from another Module's Class [duplicate]

I'm dumb and this is embarrassing, but I'm trying to figure out how I properly use a method from a class in other parts of my code. I need to understand the Drupal way, if not just the php way. I have ...
1
vote
1answer
129 views

Form state cache breaks dependency injection [duplicate]

I have a class that extends FormBase and there are 6 services that are injected into the class via Dependency Injection (DI). My problem is when I submit the form it says to a class property that ...
1
vote
1answer
934 views

Problem in dependency injection in drupal custom module service

I face with a problem in defining service in drupal 8.0 my service is : services: tracking.middleware: class: Drupal\mkt_tracking_v2\Middleware\TrackingMiddleware arguments: ['@kernel','@...
1
vote
1answer
63 views

Get Plugin Definition methods using dependency injection

It is my first time defining a custom Plugin Type. I think that this might be a comming thing in Drupal but I was not able to find any documentation anywhere. I want to get Plugin definition methods ...
1
vote
1answer
19 views

Front Blank Webpage

Hi I am working on moving my website from local to development, but get this error: Uncaught PHP Exception InvalidArgumentException: "Class "Drupal\entity\QueryAccess\ViewsQueryAlter" does not exist."...
1
vote
2answers
774 views

Dependency Injection if service exists

Is there any way to use dependency injection in a conditional way, i.e. only if a service exists similar to \Drupal::hasService(). I have a created a service in module A and in module B I have an ...