0

My project has external PHP packages pulled in via Composer.

I would like to inject one of the classes in that package as a dependency, instead of do new Class(); inside my Controller methods.

The documentation says you can define a service like the following:

services:
  mymodule.example_service:
    class: Drupal\path\to\Class

What do you do when you want to use an external PHP package not native to Drupal?

1

You should be able to use the fully qualified namespace for the injection:

services:
  mymodule.example_service:
    class: path\to\Class
0

If anyone want to use external packages into Drupal controller, note that you can actually use one without dependency injection. For example, if you want to use Carbon (DateTime API):

Step 1: Install the package

composer require nesbot/carbon

Step 2: Use the namespace

use Carbon\Carbon;

That's all. You are ready to use the package now.

Code sample:

<?php

namespace Drupal\foo\Controller;

use Carbon\Carbon;
use Drupal\Core\Controller\ControllerBase;

class FooController extends ControllerBase {

    public function bar() {
        return [
            '#markup' => Carbon::now(),
        ];
    }
}

?>
  • 1
    It’s best practice to adhere to DI as much as possible. In this example you are using a static method, similar to what Url and Link classes have. – Kevin Jun 10 '18 at 13:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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