How to create custom module in Drupal 8
In Drupal 8, we should keep the custom or contributed modules under modules folder in the root directory.
First of all I am going to create a folder for custom module that is "Custom Module" with a machine name of custom_module.
Start the module by creating a folder within the Drupal installation and path is: /modules/custom/custom_module or /sites/all/modules/custom/custom_module.
custom_module.info.yml : Now Creating the "custom_module.info.yml" in the root of the custom_module directory.
1. File: modules/custom/custom_module/custom_module.info.yml:
File: modules/custom/custom_module/custom_module.info.yml:
name: My custom module name
description: Creates a page showing "Hello World".
package: Custom
type: module
core: 8.x
2. File: modules/custom/custom_module/custom_module.module: This file is required but can be empty.
<?php
/**
* @file
* Hello module.
*/
3. File: modules/custom/custom_module/custom_module.routing.yml: This file is required but can be empty.
hello_world:
path: '/hello_world'
defaults:
_title: 'Hello Title'
_controller: '\Drupal\custom_module\HelloController::content'
requirements:
_permission: 'access content'
4. File: modules/custom/custom_module/src/HelloController.php:
In Drupal 8, classes will be autoloaded based on the PSR-4 namespacing convention.
In core, the PSR-4 'tree' starts under core/lib/.
In modules, including contrib, custom and those in core, the PSR-4 'tree' starts under modulename/src.
Defining a class in our module's .module file is only possible if the class does not have a superclass which might not be available when the .module file is loaded. It's best practice to move such classes into a PSR-4 source directory.
<?php
/**
* @file
* Contains \Drupal\custom_module\HelloController.
*/
namespace Drupal\custom_module;
use Drupal\Core\Controller\ControllerBase;
class HelloController extends ControllerBase {
public function content() {
return array(
'#markup' => '' . t('Hello there!') . '',
);
}
}
Here Namespaces are a way of organizing codebases. Namespaces documentation on php.net.
5. Go to module list page and enable the custom module and visit the path.
Comments
Post a Comment