Take the 2-minute tour ×
Drupal Answers is a question and answer site for Drupal developers and administrators. It's 100% free, no registration required.

In Drupal 7 module development, I could include a custom inc, api, or php class file using the file[]= directive in the module.info file or the drupal_load_included() function.

With D8 using PSR, what is the proper way to package up a "plain ole PHP object" and reference it in DefaultController.php? Think something like: $a = new POPO();.

Is just giving the PHP file containing the class a namespace sufficient? How does the controller (or module in general) know to reference or scan for that class?

share|improve this question
    
This link Creating Drupal 8.x modules might be helpful –  Krishna Mohan Sep 3 at 14:33
    
Yes, I've read through drupal.org/node/2087879 but upon not seeing the file[]= directive, it unfortunately didn't answer this specific question of file inclusion. –  Richard Sep 3 at 15:34

1 Answer 1

up vote 5 down vote accepted

You don't use file[] = ... anymore. Instead, classes are autoloaded. For example, I have a module with the following file structure:

  • views_hybrid/
    • views_hybrid.info.yml
    • views_hybrid.module
    • src/
      • Plugin/
        • Field/
          • FieldFormatter/
            • HybridFormatter.php

HybridFormatter.php defines a class called HybridFormatter.

In my .module file, if I start typing in my IDE (NetBeans in this case) HybridFormatter it autocompletes to \Drupal\views_hybrid\Plugin\Field\FieldFormatter\HybridFormatter:: because it is autoloaded. Since I don't want that whole path littering my module, at the top I have placed the line,

use Drupal\views_hybrid\Plugin\Field\FieldFormatter\HybridFormatter;

along with use directives for other classes I am including for use with my module.

The namespace is defined in HybridFormatter.php like so:

namespace Drupal\views_hybrid\Plugin\Field\FieldFormatter;

class HybridFormatter extends FormatterBase { ... }
share|improve this answer
    
So to ensure I fully understand, HybridFormatter.php will be autoloaded... automatically? There is no need for an include_once()? Does HybridFormatter.php have a namespace defined? –  Richard Sep 3 at 18:26
    
There is no need for include_once or require_once or anything. Hybridformatter.php does define a namespace. I'll include in the answer. –  betherwisser Sep 3 at 18:44

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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