sharing code in custom module 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

&lt;?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

&lt;?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

&lt;?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
If you want the class declared in my_module/src/Utils.php to be made available to any PHP script, add this at the top of that script file:

use Drupal\my_module\Utils;


This of course assumes that you're following the correct PSR-4 standards for naming: make sure that mymodule/src/Utils.php exists, and contains one single class named Utils, with namespace Drupal\my_module at the top.

See PSR-4 namespaces and autoloading in Drupal 8 for a more in-depth explanation.