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
0 votes
0 answers
36 views

Container is not initialized error in unit test

I am trying to test a class method that instantiate some other classes and my unit test failed due to those object. Here is my method for testing: public function setTimezoneForDatetime($datetime) { ...
  • 131
0 votes
1 answer
115 views

getStorage() on null when using entityTypeManager in form

I'm trying to use dependency injection correctly in a custom form but I'm getting an error when trying to access entityTypeManager. <?php namespace Drupal\my_module\Form; use Drupal\Core\Form\...
2 votes
1 answer
120 views

how to extend existing drush command class

Can anyone please let me know how to extend existing drush command class. I am writing a custom module which provides custom content entity and created a devel generate plugin similar to ...
0 votes
0 answers
352 views

The service "redirect.request_subscriber" has a dependency on a non-existent service "path_alias.manager"

We have inherited a Multisite Drupal setup and are managing the migration for a client. We have the codebase set up locally and have two of the sites up and running. We are hitting an error on the ...
2 votes
1 answer
82 views

Dependency injection in FieldItemList

I'm creating a few custom classes that extend FieldItemList and they need some services injected. I've had a look at core classes that extend that class and none of them do dependency injection, they ...
  • 652
1 vote
1 answer
390 views

TypeError: Argument 1 passed to ........ ::__construct() must implement interface Drupal\Core\Cache\CacheBackendInterface, array given, called in

I'm getting an error when I wrote the code using Dependency injection: TypeError: Argument 1 passed to Drupal\sydneypro_exchange_rates_block\Plugin\Block\ExchangeRatesBlock::__construct() must ...
  • 11
-1 votes
2 answers
95 views

Dependency injection in create() method of block plugin with derivatives

I am trying to extend the menu_block module to allow it to work with domains (via the domain module). In order to do this I am extending the MenuBlock class, and trying to access the domain.negotiator ...
2 votes
2 answers
453 views

"RuntimeException: You have requested a non-existent parameter 'app.root'"

After I clear the cache, I get this message. Symfony\Component\DependencyInjection\Exception\RuntimeException: You have requested a non-existent parameter "app.root". in Symfony\Component\...
1 vote
2 answers
125 views

How can I inject dependencies based on conditions?

I am creating one custom form and in this form I need to use one service which are there in another module. I need to use that dependency injection based on condition which are there in configuration. ...
  • 223
0 votes
2 answers
116 views

How do I use DependencySerializationTrait?

I'm on Drupal 9. I'm trying to edit the ProductVariationAccessControlHandler class of Commerce. The class extends Drupal\Core\Entity\EntityAccessControlHandler which in turn extends the abstract class ...
  • 510
3 votes
1 answer
282 views

Which is better way of injecting service to controller with __construct or $instance = parent::create($container)

I'm always using this way of injecting service to controller: <?php namespace Drupal\TestModule\Controller; use Drupal\Core\Controller\ControllerBase; use Symfony\Component\...
  • 31
0 votes
0 answers
29 views

Transform the view mode of a content type into the class of the body

I want to add the view mode of my content type as a class to body and I use Display Suite so $node['view_mode'] is not available. In MYTHEME_preprocess_html(&$variables), I injected the service \...
  • 233
1 vote
1 answer
77 views

Can I use the session service directly instead of via the request?

The Drupal documentation on sessions mentions that sessions can be accessed via the Request object: Session data is accessed via the \Symfony\Component\HttpFoundation\Request::getSession() method, ...
  • 8,239
1 vote
2 answers
225 views

Injecting a NEW instance of a service into another service class

I have a service (for sending error alerts) which is used by multiple other services. The alert service is injected into those classes via the relevant services.yml files and through their ...
  • 433
0 votes
0 answers
67 views

How to use methods from entity class if it doesn't have such service?

I'm writing an EventSubscriber for the config entity of the domain module. My goal is to insert some data in its config on preSave event (it becomes from the patch for D9). Here is my code from ...
1 vote
2 answers
574 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 ...
1 vote
1 answer
163 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 ...
  • 111
0 votes
0 answers
129 views

Use Injected CacheBackedInterface to invalidate certain bin

I've got a content type called SERVICE (I write it all capitalized to prevent mixture with drupal service) which admin can introduce different SERVICE using this type, it is expected that these ...
1 vote
1 answer
565 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 ...
  • 480
1 vote
1 answer
91 views

New module service is dependency on old module service - The service has a dependency on a non-existent service

I have a new module moduleB. It defines a service that is used in the dependency injection of moduleA. moduleA is already enabled, its changes are just to the services definition. The info.yml has ...
  • 738
0 votes
0 answers
81 views

Discover custom services with drush generate

When I create a module and a custom service with drush generate and then create another service, also with drush generate, the first one is not available to inject. What is missing to make it become ...
1 vote
1 answer
69 views

Missing proxy classes when container compiles custom ExtensionPass

Context I try to find a way to integrate Webpack Encore into Drupal. Since we can't use Symfony Bundles in Drupal I want to port the bundle to a custom Drupal module. What I have done so far To ...
1 vote
1 answer
303 views

How to inherit base class dependencies without redefining theme in child class service arguments?

The current system I have a set of services classes that extends the same base class ex: class NodeHandler extends ContentEntityHandlerBase {} class ParagraphHandler extends ContentEntityHandlerBase {}...
2 votes
1 answer
377 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\...
1 vote
1 answer
760 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,988
0 votes
2 answers
356 views

Drupal 8 service dependency injection [closed]

I am trying to build a service that will leverage the Pathauto service so my class looks like this. namespace Drupal\some_system; use Drupal\pathauto\PathautoGenerator; use Drupal\pathauto\...
  • 335
0 votes
1 answer
178 views

Replace \Drupal::service with Dependency injection in FieldWidget class

I have created an ajax callback inside a custom Field Widget plugin. In the Ajax callback I have called a custom service using $service = \Drupal::service('service.name') I am using phpmd to clean ...
  • 846
2 votes
2 answers
94 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 ...
6 votes
1 answer
637 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 ...
4 votes
0 answers
745 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 ...
  • 3,472
2 votes
0 answers
57 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 ...
  • 121
0 votes
2 answers
1k views

How can I inject container to a class with constructor having arguments?

Fatal error: Declaration of Drupal\migrate_upgrade\MigrateUpgradeDrushRunner::create(Psr\Container\ContainerInterface $container, $options = Array) must be compatible with Drupal\Core\...
  • 4,279
0 votes
1 answer
84 views

How to use service container correcly?

I want to use service container inside my class so I have this this: class SomeController extends ControllerBase { protected $entityTypeManager; protected $requestStack; public function ...
1 vote
1 answer
211 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 ...
0 votes
1 answer
713 views

How to call method of controller in .module file with dependency injection

I have class named Book. class Popups { private $entityQuery; private $entityTypeManager; public function __construct(QueryFactory $entityQuery, EntityTypeManagerInterface $entity_type_manager)...
  • 145
-1 votes
1 answer
129 views

What is the logic of create method in ContainerInterface class & its argument when being used and how its related to argument of the construct method?

<?php namespace Drupal\custom_changes\Plugin\Block; use Drupal\Core\Block\BlockBase; use Drupal\Core\Form\FormStateInterface; use Drupal\Core\Plugin\ContainerFactoryPluginInterface; use Symfony\...
  • 4,279
4 votes
3 answers
1k 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 ...
0 votes
1 answer
177 views

how to extend FormBuilder::processForm from multiple API endpoints in one class

I'm trying to consolidate my form processing by entity_type, without rebuilding the forms (just using the default forms provided by Drupal. I have dynamic routes pointing to a _controller::method. I'...
  • 374
0 votes
0 answers
492 views

dependency injection by using $this when not in object context

if i´m using the codesniffer function i´m getting two warnings about: 155 | WARNING | \Drupal calls should be avoided in classes, use dependency injection instead If i´m changing the line from: $...
1 vote
2 answers
880 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
1 answer
1k 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','@...
0 votes
1 answer
57 views

How Webprofiler EntityManagerWrapper overrides EntityTypeManager?

In trying to understand the new paradigm of Dependency Injection, I attempted to install Webprofiler into my D8.6.10 project but it seemed it causes a conflict with my already installed ...
  • 439
3 votes
1 answer
3k 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 ...
  • 480
1 vote
1 answer
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."...
0 votes
0 answers
533 views

Using a class to call a call a custom drush service

I have created a drush service and I can use it on the command line, but I am trying to use dependency injection to use it from another class. However, it is saying that the service cannot be found. (...
1 vote
1 answer
82 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 ...
's user avatar
0 votes
1 answer
741 views

How to properly call dependency classes (Class not found)

I'm creating a custom module that uses PHPMailer, which has been installed in the module's vendor folder via composer. This is the error I get: Error: Class 'PHPMailer' not found in Drupal\multisend\...
0 votes
1 answer
306 views

Instantiate Controller with Interface not concrete class [closed]

As background, I am rebuilding some old code and want to wrap all the curl based requests in an interface (HttpRequestInterface) so I can swap that out later without having to write all the api calls ...
  • 103
1 vote
2 answers
1k 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 ...
  • 11
1 vote
2 answers
125 views

Issue with the cognito module

I am running into the below issue : The website encountered an unexpected error. Please try again later.InvalidArgumentException: Class "\Drupal\cognito\Form\Email\UserLoginForm" does ...