2

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('block_plugins');

It's worked, but I always see the warning.

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

I have the similar with File::load(), too. I used:

use Drupal\file\Entity\file;
class BXBlock extends BlockBase {
public function build() {
...
$file = File::load($value);
...
}
}

Anybody can help me, please? Thanks so much.

1 Answer 1

5

You can check how the dependency injection works in general in this documentation. https://www.drupal.org/docs/8/api/services-and-dependency-injection/dependency-injection-for-a-form

The parts that you need are:

Use statement -

 use Symfony\Component\DependencyInjection\ContainerInterface;

Class property - here we are going to store the whole \Drupal::service('current_user') object.

 protected $account;

The __construct magic method. This is called upon instantiating the class. The dependency injection bit here is providing all the data required in a later stage as input.

function __construct(AccountInterface $account) {

Built in method that has a dependency injection create(ContainerInterface $container)

return new static(
  // Load the service required to construct this class.
  $container->get('current_user')
);

Eventually we are using the whole construction like that:

$uid = $this->account->id();

where $this->account is the same like \Drupal::service('current_user');

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.