怎样编写Drupal 8模块

By admin, 5 二月, 2015

此文章已过时,Drupal 8的API已修改,请参考examples/page_example

 

Drupal 8约定把所有自定义的模块都放在了根目录下的modules了,创建自己的模块先创建如下目录:modules/foobar,里面包含文件foobar.modulefoobar.info.yml。foobar.info.yml内容如下:

name: Foobar
type: module
description: 'This is a demo for creating Drupal 8 modules.'
package: Custom
version: 8.x-1.0
core: 8.x
dependencies:
- node
- block
hidden: false
Drupal 8使用了MVC的设计模式,下面创建一个Controller,目录结构为:modules/foobar/src/Controller/FoobarController.php
 
<?php
 
namespace Drupal\foobar\Controller;
 
use Drupal\Core\Controller\ControllerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
 
class FoobarController implements ControllerInterface {
 
  public static function create(ContainerInterface $container) {
    return new static($container->get('module_handler'));
  }
 
  /**
  * This will return the output of the foobar page.
  */
  public function foobarPage() {
    return array(
      '#markup' => t('This is the demo foobar page.'),
    );
  }
}
之后就是添加路由:modules/foobar/foobar.routing.yml
foobar:
pattern: 'admin/foobar'
defaults:
  _content: '\Drupal\foobar\Controller\FoobarController::foobarPage'
requirements:
  _permission: 'access administration pages'
同时需要在foobar.module里添加菜单注册:

 
<?php
 
/**
* Implements hook_menu().
*/
function foobar_menu() {
  // The paths given here need to match the ones in foobar.routing.yml exactly.
  $items['admin/foobar'] = array(
    'title' => 'Foobar',
    'description' => 'This is the demo foobar page.',
    // The name of the route from foobar.routing.yml
    'route_name' => 'foobar',
  );
  return $items;
}
 

参考:http://getlevelten.com/blog/ian-whitcomb/drupal-8-module-development-part-1-getting-started

标签

评论1

Restricted HTML

  • 允许的HTML标签:<a href hreflang> <em> <strong> <cite> <blockquote cite> <code> <ul type> <ol start type> <li> <dl> <dt> <dd> <h2 id> <h3 id> <h4 id> <h5 id> <h6 id> <img src>
  • 自动断行和分段。
  • 网页和电子邮件地址自动转换为链接。
验证码
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.
请输入"Drupal10"

李洋 (未验证)

5 years 10 months 之前

我想问问,用restful 在页面生成的接口url ,我该怎么找它的控制器,找了整个模块的东西,都没有找到。
qq:1622994727

最新评论