In Drupal, PSR-4 namespaces are commonly used for organizing and autoloading custom PHP classes, including controllers. Here's how you can define a PSR-4 namespace for your custom module in Drupal:
Step 1: Module Structure
Ensure your module follows the standard Drupal module structure. Your module folder should be located in the modules/custom directory of your Drupal installation. For example, if your module is named "custom_hello", the folder structure would look like this:
modules/
└── custom/
└── custom_hello/
├── src/
│ └── Controller/
│ └── CustomHelloController.php
└── custom_hello.info.yml
Step 2: Define PSR-4 Autoloading in the .info.yml File
In your module's .info.yml file (custom_hello.info.yml in this example), specify the PSR-4 autoloading for your module's namespace. Here's an example:
name: 'Custom Hello'
type: module
description: 'Defines a custom controller to say hello.'
core_version_requirement: ^8 || ^9
package: Custom
autoload:
psr-4:
Drupal\custom_hello\: src/
This configuration tells Drupal to look for classes with the namespace Drupal\custom_hello inside the src/ directory of your module.
Step 3: Define Your Controller Class
Create your controller class file (CustomHelloController.php in this example) inside the appropriate directory according to the namespace you defined. Make sure the namespace and class name match the PSR-4 namespace you specified in the .info.yml file. Here's an example:
// File: custom_hello/src/Controller/CustomHelloController.php
namespace Drupal\custom_hello\Controller;
use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\HttpFoundation\Response;
/
* Controller for the custom hello message.
*/
class CustomHelloController extends ControllerBase {
/
* Returns a simple hello message.
*/
public function hello() {
// Create the message.
$message = 'Hello, Drupal!';
// Return a response with the message.
return new Response($message);
}
}
Conclusion
By defining a PSR-4 namespace in your module's .info.yml file and organizing your classes accordingly, Drupal can autoload your custom classes, including controllers, making it easier to manage and maintain your module's codebase.
Comments