官术网_书友最值得收藏!

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!

主站蜘蛛池模板: 盐边县| 四川省| 同心县| 康定县| 明溪县| 尼勒克县| 巴林右旗| 涟源市| 汝阳县| 望都县| 庆安县| 九寨沟县| 融水| 安陆市| 麻江县| 佛坪县| 峨边| 偃师市| 育儿| 宣城市| 内乡县| 兴安县| 崇礼县| 金门县| 屏东市| 梨树县| 阜康市| 肃南| 沭阳县| 增城市| 德格县| 将乐县| 洪江市| 澄城县| 布尔津县| 禄丰县| 崇明县| 阿瓦提县| 紫金县| 丰原市| 望江县|