I have a small module that basically contains a controller and a block plugin. I cannot figure out how to include a class in both of them
The files are located in sites/all/modules/my_module. That directory contais
$ ls -R
.:
config/ my_module.info.yml my_module.links.menu.yml src/
css/ my_module.libraries.yml my_module.routing.yml
./config:
install/
./config/install:
my_module.settings.yml
./css:
hello_block-layout.css
./src:
Controller/ Plugin/ Utils.php
./src/Controller:
MyController.php*
./src/Plugin:
Block/
./src/Plugin/Block:
MyBlock.php
The problem is the namespaces: MyController.php has namespace Drupal\my_module\Controller and MyBlock.php has namespace Drupal\my_module\Plugin\Block
I can use the class definition in Utils.php for one of the two, if I insert a require_once in the file (with the whole path, use of .. seems not to be working) AND I use the same namespace in it.
So if MyController.php starts with
<?php
namespace Drupal\my_module\Controller;
use Drupal\Core\Controller\ControllerBase;
require_once '/home/rdgon/public_html/sites/all/modules/my_module/src/Utils.php';
and MyBlock.php starts with
<?php
namespace Drupal\my_module\Plugin\Block;
use Drupal\Core\Block\BlockBase;
use Drupal\Core\Block\BlockPluginInterface;
require_once '/home/rdgon/public_html/sites/all/modules/my_module/src/Utils.php';
and Utils.php starts with
<?php
namespace Drupal\my_module\Controller;
then the class is used by correctly by the controller. But then MyBlock.php complains about not finding the class, because the namespaces don't match.
My question: is it possible to share (include) a class definition by several components of a module? What location should I use for the shared code and what is the proper way to include it? (using the full path of the file cannot be the way to go)
thanks in advance, Ruud
use
statement and dependency injection. Look at core Unicode class for another example. Or define it as a service. The auto loaded will figure it all out for you.