此文章已过时,Drupal 8的API已修改,请参考examples/page_example
Drupal 8约定把所有自定义的模块都放在了根目录下的modules了,创建自己的模块先创建如下目录:modules/foobar,里面包含文件foobar.module和foobar.info.yml。foobar.info.yml内容如下:
name: Foobartype: moduledescription: 'This is a demo for creating Drupal 8 modules.'package: Customversion: 8.x-1.0core: 8.xdependencies:- node- blockhidden: false
Drupal 8使用了MVC的设计模式,下面创建一个Controller,目录结构为:modules/foobar/src/Controller/FoobarController.php
<?phpnamespace 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
restful
我想问问,用restful 在页面生成的接口url ,我该怎么找它的控制器,找了整个模块的东西,都没有找到。
qq:1622994727