- Drupal 8 Module Development
- Daniel Sipos
- 317字
- 2021-07-02 12:22:38
The Controller
Now that we have found out more or less where we have to place our Controller, let's begin by creating a Controller folder inside our module's /src folder. Although not mandatory, this is a standard practice for Controller placement. Inside this folder, we can have our first Controller class file: HelloWorldController.php.
Inside the file, we again have something simple (after the opening PHP tags):
namespace Drupal\hello_world\Controller;
use Drupal\Core\Controller\ControllerBase;
/**
* Controller for the salutation message.
*/
class HelloWorldController extends ControllerBase {
/**
* Hello World.
*
* @return array
*/
public function helloWorld() {
return [
'#markup' => $this->t('Hello World')
];
}
}
As expected, we start with the namespace declaration. If you read the preceding section, the namespace choice will make sense. Then, we have our Controller class that extends the Drupal 8 ControllerBase, which happens to provide some helper tools (such as the StringTranslationTrait, which I will explain later in the book when we talk about languages). If you remember our route definition, we have a helloWorld method that returns an array.
If you've worked with previous versions of Drupal, this array (called a render array) will be familiar. Otherwise, what you need to know right now is that we are returning simple markup with the Hello World text wrapped in the translation service I hinted at in the previous paragraph. After the Controller returns this array, there will be an EventSubscriber that takes this array, runs it through the Drupal theme layer, and returns the HTML page as a response. The actual content returned in the Controller will be wrapped in the Main page content block that is usually placed in the main content region of the theme.
Now, our simple Controller is done. If we clear the cache and go to /hello, we should encounter a new page that outputs the Our first route title and the Hello World content. Success!

- Mobile Application Development:JavaScript Frameworks
- Java面向對象軟件開發
- Learning Docker
- 深入淺出Prometheus:原理、應用、源碼與拓展詳解
- C和C++安全編碼(原書第2版)
- x86匯編語言:從實模式到保護模式(第2版)
- Scratch 3游戲與人工智能編程完全自學教程
- C語言程序設計
- 網站構建技術
- 青少年信息學競賽
- Python深度學習:模型、方法與實現
- MySQL入門很輕松(微課超值版)
- Mudbox 2013 Cookbook
- WordPress Search Engine Optimization(Second Edition)
- 算法訓練營:海量圖解+競賽刷題(入門篇)