Drupal 8 并未使用 MVC 架构模式,它只实现了控制器编程模型
路由:url映射到控制器。控制器:一个PHP函数,处理http请求,构造并返回http响应。
创建一个新的模块
- modules里面新建一个文件夹,里面包含 page_example.info.yml
name: 'Page example'
type: module
description: 'An example module showing how to define a page to be displayed at a given URL.'
package: 'Example modules'
core: 8.x
extends, 可以找到这个模块,然后激活就行了。
- 创建page_example.routing.yml 路由管理文件。
page_example_description:
path: '/examples/page_example'
defaults:
_controller: '\Drupal\page_example\Controller\PageExampleController::description'
requirements:
_access: 'TRUE'
page_example_simple:
path: '/examples/page_example/simple'
defaults:
_controller: '\Drupal\page_example\Controller\PageExampleController::simple'
requirements:
_permission: 'access simple page'
- 创建controller
模块中创建src/Controller文件夹,然后PageExampleController.php
<?php
/**
* @file
* Contains \Drupal\page_example\Controller\PageExampleController.
*/
namespace Drupal\page_example\Controller;
use Drupal\Core\Url;
/**
* Controller routines for page example routes.
*/
class PageExampleController {
/**
* Constructs a page with descriptive content.
*
* Our router maps this method to the path 'examples/page_example'.
*/
public function description() {
$simple_url = Url::fromRoute('page_example_simple');
$simple_link = \Drupal::l(t('simple page'), $simple_url);
$arguments_url = Url::fromRoute('page_example_description', [], ['absolute' => TRUE]);
$arguments_link = \Drupal::l(t('arguments page'), $arguments_url);
$build = [
'#markup' => t(
'<p>The Page example module provides two pages, "simple" and "arguments".</p>'
. '<p>The !simple_link just returns a renderable array for display.</p>'
. '<p>The !arguments_link takes two arguments and displays them, as in @arguments_url</p>',
[
'!simple_link' => $simple_link,
'!arguments_link' => $arguments_link,
'@arguments_url' => $arguments_url->toString()
]
),
];
return $build;
}
/**
* Constructs a simple page.
*
* The router _controller callback, maps the path 'examples/page_example/simple'
* to this method.
*
* _controller callbacks return a renderable array for the content area of the
* page. The theme system will later render and surround the content with the
* appropriate blocks, navigation, and styling.
*/
public function simple() {
return [
'#markup' => '<p>' . t('Simple page: The quick brown fox jumps over the lazy dog.') . '</p>',
];
}
}
- 创建菜单page_example.links.menu.yml
page_example.description:
title: 'Page Example'
route_name: page_example_description
parent: system.admin_reports
page_example.simple:
title: 'Simple - no arguments'
route_name: page_example_simple
parent: system.admin_reports
parent 的值是父菜单链接机器名,确定这个需要对 *.links.menu.yml 进行些调查。管理界面菜单定义在核心 System 模块内,因此需要查看 system.links.menu.yml 文件来确定这个值。
清空缓存:
#composer config -g repo.packagist composer https://packagist.phpcomposer.com
#composer require drupal/drush
drush cr
网友评论