Create a Module with a Route and Controller

Video loading...

  • 0:04
    Create a Module with a Route and Controller with Ryan Weaver
  • 0:08
    Let's do something fun like create a custom page.
  • 0:12
    Like always, any custom code will live in a module.
  • 0:15
    And modules live in the modules directory.
  • 0:20
    Create a new one called dino_roar. To make Drupal fall in love with your module,
  • 0:24
    create the info file, dino_roar.info.yml.
  • 0:29
    If you love the old info files, then you'll feel all warm and fuzzy with these.
  • 0:34
    It's the same exact thing but now in the YAML format.
  • 0:38
    Inside, give it a name, Dino ROAR; a type, module; description, roar at you;
  • 0:46
    package, sample; and core, 8.x.
  • 0:54
    If YAML is new to you, cool. It's pretty underwhelming.
  • 0:57
    Just a colon separated key value pair.
  • 1:01
    But make sure you have at least one space after the colon.
  • 1:03
    YAML also supports hierarchies of data via indentation, but there's none of that in this file.
  • 1:09
    Module ready. Head back to the browser and go into the Extend section.
  • 1:15
    With any luck we'll see the module here.
  • 1:19
    There it is under Sample, Dino ROAR. Sounds terrifying.
  • 1:23
    Check the box and press the Install button anyways.
  • 1:27
    What's the worst that could happen?
  • 1:29
    Nothing. But now we can build that page I keep talking about.
  • 1:32
    In any modern framework, and I am including Drupal in this category,
  • 1:38
    creating a page is two steps.
  • 1:41
    First define the URL for the page via a route.
  • 1:44
    That's your first buzzword in case you're writing things down.
  • 1:47
    Second, create a controller for that page.
  • 1:50
    This is a function that you'll write that actually builds the page.
  • 1:54
    It's also another buzzword, controller.
  • 1:57
    If these are new buzzwords for you, that's okay. They're just a new spin on some old ideas.
  • 2:04
    For step one, create a new file in the module dino_roar.routing.yml.
  • 2:11
    Create a new route called dino_says: This is the internal name of the route,
  • 2:16
    and it isn't important yet. Go in four spaces, or two spaces,
  • 2:21
    it doesn't matter. Just be consistent. And add a new property to this route called path:.
  • 2:27
    Set it to /the/dino/says, the URL to the new page.
  • 2:32
    Oh, by the way, the standard is two spaces in YAML files,
  • 2:36
    not four. I'm using four because that's what we use in the Symfony world.
  • 2:40
    Either way it will work.
  • 2:43
    Below path, a few more properties are needed. The first is defaults:
  • 2:47
    with an _controller: key beneath it.
  • 2:49
    The _controller: key tells Drupal which function should be called
  • 2:54
    when someone goes to the URL for this exciting page.
  • 2:57
    Set this to Drupal\dino_roar\controller\RoarController::roar
  • 3:07
    This is a namespaced class followed by :: and then a method name.
  • 3:12
    We'll create this function in a second.
  • 3:16
    Also add a requirements: key with an _permission: key set to access content.
  • 3:22
    We won't talk about permissions now, but this is what will allow us to view the page.
  • 3:27
    In YAML you usually don't need quotes except in some edge cases with special characters.
  • 3:33
    But it's always safe to surround values with quotes.
  • 3:36
    So if you're in doubt, use quotes. I don't need them around access content,
  • 3:41
    but it makes me feel all warm and fuzzy.
  • 3:44
    Step one complete, we have a route. For step two we need to create the controller,
  • 3:49
    the function that will actually build the page.
  • 3:53
    Inside of the Dino ROAR module, create an src directory and then a Controller directory inside of that.
  • 4:01
    Finally add a new PHP Class called RoarController.
  • 4:07
    Okay stop. Fun fact. Every class you create will have a namespace at the top.
  • 4:14
    If you're not comfortable with namespaces,
  • 4:16
    they're really easy, so easy that we teach them to you
  • 4:20
    in 120 seconds in our namespaces tutorial.
  • 4:23
    So pause this video, check that out, and then everything we're about to do
  • 4:26
    will seem much more awesome.
  • 4:29
    But you can't just set the namespace to any old thing.
  • 4:33
    There are rules, people. It must start with Drupal\, then the name of the module,
  • 4:38
    dino_roar\, then whatever directory or directories this file lives in after src.
  • 4:46
    This class lives in Controller.
  • 4:52
    Your class name also has to match the file name, plus .php.
  • 4:57
    If you mess any of this up, Drupal isn't going to be able to find your class.
  • 5:02
    The full class name is now
  • 5:04
    Drupal\dino_roar\Controller\RoarController.
  • 5:08
    Hey, this conveniently matches the _controller of our route.
  • 5:16
    In RoarController, add the new public function roar.
  • 5:19
    Now you might be asking yourself what a controller function like this should return.
  • 5:23
    And to that I say excellent question. Brilliant.
  • 5:27
    A controller should always return a Symfony response object.
  • 5:30
    Okay, that's not 100% true, but let me lie for just a little bit longer.
  • 5:37
    To return a response, say return new Response.
  • 5:42
    I'll let it autocomplete the response class from Symfony's http foundation namespace.
  • 5:47
    When I hit tab to select this, PhpStorm adds the use statement to the top of the class automatically.
  • 5:52
    And that's important. Whenever you reference a class, you must add a use statement for it.
  • 5:58
    If you forget, you'll get the famous class not found error.
  • 6:02
    For the page content, we will, of course, rooooooar.
  • 6:07
    That's it. That's everything. Go to your browser
  • 6:10
    and head to /the/dino/says.
  • 6:20
    Hmm, page not found.
  • 6:22
    As a seasoned Drupal developer, you may be wondering,
  • 6:25
    do I need to clear some cache?
  • 6:28
    My gosh, you're right.
  • 0:04
    Carregar e Salvar Dados de Entidades de Configurações Traduzido em parceria com a MMDA (http://www.mmda.com.br)
  • 0:08
    Vamos fazer algo divertido como criar uma página customizada.
  • 0:12
    Como sempre, qualquer código customizado irá morar em um módulo.
  • 0:15
    E módulos moram no diretório modules.
  • 0:20
    Crie um novo chamado dino_roar. Para fazer com que o Drupal se apaixone pelo seu módulo,
  • 0:24
    crie o arquivo info, dino_roar.info.yml.
  • 0:29
    Se você ama os arquivos info antigos, então você irá se sentir alegre e entusiasmado com esses.
  • 0:34
    É exatamente a mesma coisa mas agora no formato YAML.
  • 0:38
    Dentro, dê um name, Dino ROAR; um type, module; description, roar at you;
  • 0:46
    package, sample; e core, 8.x
  • 0:54
    Se YAML é novo para você, tudo bem. É bastante agradável.
  • 0:57
    Apenas um par de chave e valor separado por dois pontos.
  • 1:01
    Mas tenha certeza que você tem ao menos um espaço depois dos dois pontos.
  • 1:03
    O YAML suporta hierarquias de dados através de identação, mas não há nenhuma nesse arquivo.
  • 1:09
    Módulo pronto. Volte para o navegador e vá para a seção Extend.
  • 1:15
    Com qualquer sorte, você irá ver o módulo aqui.
  • 1:19
    Ali está, abaixo de Sample, Dino ROAR. Soa aterrorizante.
  • 1:23
    Marque a caixa e pressione o botão Install, de qualquer maneira.
  • 1:27
    Poderia acontecer algo pior?
  • 1:29
    Nada. Mas agora podemos construir aquela página que tenho falado sobre.
  • 1:32
    Em qualquer framework moderno, e eu estou incluindo Drupal nessa categoria,
  • 1:38
    criar uma página são dois passos.
  • 1:41
    Primeiro, defina a URL para a página através da rota.
  • 1:44
    Essa é sua primeira palavra da moda, caso você esteja escrevendo as coisas.
  • 1:47
    Segundo, crie um controller para essa página.
  • 1:50
    Isso é uma função que você irá escrever que irá na verdade construir aquela página.
  • 1:54
    É também outra palavra da moda, controller.
  • 1:57
    Se essas são novas palavras da moda para você, está okay. Elas são apenas um novo giro em ideias antigas.
  • 2:04
    Para o primeiro passo, crie um novo arquivo no módulo, dino_roar.routing.yml.
  • 2:11
    Crie uma nova rota chamada dino_says: Esse é o nome interno da rota,
  • 2:16
    e não é importante ainda. Vá 4 espaços a frente, ou dois,
  • 2:21
    não importa. Apenas seja consistente. Adicione uma nova propriedade para essa rota chamada path:
  • 2:27
    Defina-a para /the/dino/says, a URL para a nova página.
  • 2:32
    Oh, a propósito, o padrão é dois espaços em arquivos YAML,
  • 2:36
    não quatro. Estou usando quatro porque é isso que usamos no mundo Symfony.
  • 2:40
    De qualquer maneira irá funcionar.
  • 2:43
    Abaixo de path, mais algumas propriedades são necessárias. A primeira é defaults:
  • 2:47
    com uma chave _controller: abaixo dela.
  • 2:49
    A chave _controller: diz ao Drupal qual função deve ser chamada
  • 2:54
    quando alguém vai para a URL para essa página emocionante.
  • 2:57
    Defina isso para Drupal\dino_roar\controller\RoarController::roar
  • 3:07
    Isso é uma classe com namespace seguida por :: e o nome do método.
  • 3:12
    Iremos criar essa função em um segundo.
  • 3:16
    Também adicione uma chave requirements: com uma chave _permission: e defina-a para "access content"
  • 3:22
    Não iremos falar sobre permissões agora, mas isso é o que nos permitirar ver a página.
  • 3:27
    No YAML você normalmente não precisa de aspas ao menos em alguns casos de uso extremos com caracteres especiais.
  • 3:33
    Mas é sempre seguro cercar valores com aspas.
  • 3:36
    Então se você está em dúivida, use aspas. Eu não preciso delas em roda do access content,
  • 3:41
    mas isso faz com que me sinta alegre e entusiasmado.
  • 3:44
    Passo um completo, temos uma rota. Para o passo dois, precisamos criar o controller,
  • 3:49
    a função que irá de fato construir a página.
  • 3:53
    Dentro do módulo Dino ROAR, crie um diretório src e depois um diretório Controller dentro dele.
  • 4:01
    Finalmente, adicione uma nova classe PHP chamada RoarController.
  • 4:07
    Okay, pare. Fato divertido. Cada classe que você cria terá um namespace no topo.
  • 4:14
    Se você não está confortável com namespaces,
  • 4:16
    eles são realmente fáceis, tão faceis que iremos ensina-los a você
  • 4:20
    em 120 segundos com nosso tutorial de namespaces.
  • 4:23
    Então pause esse vídeo, verifique esse tutorial, e depois tudo que estamos prestes a fazer
  • 4:26
    irá parecer muito mais impressionante.
  • 4:29
    Mas você não pode apenas definir o namespace para qualquer coisa velha.
  • 4:33
    Há regras, pessoas. Isso precisa começar com Drupal\, depois o nome do módulo,
  • 4:38
    dino_roar\, depois qualquer diretório ou diretórios em que esse arquivo mora, depois de src.
  • 4:46
    Essa classe mora em Controller.
  • 4:52
    O nome da sua classe tem que corresponder o nome do arquivo, mais .php
  • 4:57
    Se você bagunçar qualquer parte disso, o Drupal não poderá encontrar sua classe.
  • 5:02
    O nome completo da classe é agora
  • 5:04
    Drupal\dino_roar\Controller\RoarController.
  • 5:08
    Ei, isso corresponde convenientemente o _controller da nossa rota.
  • 5:16
    No RoarController, adicione uma nova função pública roar.
  • 5:19
    Agora você talvez esteja se perguntando o quê uma função controller como essa deveria retornar.
  • 5:23
    E para isso eu digo, excelente questão. Brilhante.
  • 5:27
    Um controller sempre deve retornar um objeto de resposta Symfony.
  • 5:30
    Okay, isso não é 100% verdade, mas deixe-me mentir por um pouco mais de tempo.
  • 5:37
    Para retornar uma resposta, diga return new Response.
  • 5:42
    Irei deixar isso autocompletar a classe de resposta do namespace Symfony HTTP foundation.
  • 5:47
    Quando eu aperto tab para selecionar isso, o PHPStorm adiciona a declaração use no topo da classe automaticamente.
  • 5:52
    E isso é importante. Sempre que você referenciar uma classe, você precisa adicionar uma declaração use para ela.
  • 5:58
    Se você esquecer, você irá obter o famoso erro de classe não encontrada.
  • 6:02
    Para o conteúdo da página, nós, é claro, iremos dar um rugido, rooooooar.
  • 6:07
    É isso. Isso é tudo. Vá para seu navegador
  • 6:10
    e se dirija a /the/dino/says.
  • 6:20
    Hmm, página não encontrada.
  • 6:22
    Como um desenvolvedor Drupal amadurecido, você pode estar se questionando,
  • 6:25
    preciso limpar algum cache?
  • 6:28
    Meu Deus, você está certo.

Create a Module with a Route and Controller

Loading...

In this tutorial, we'll create a new module and create a route and controller for it. Remember hook_menu? Well, hook_menu is out and routes and controllers are in! If the YAML files in this lesson piqued your interest, check out our introduction to YAML tutorial to learn more.

Note: There is a new core_version_requirement property for info files, starting with Drupal 8.8.x, including Drupal 9.x. For Drupal sites using version 8.8 and above, instead of the core property, use core_version_requirement. In most cases, adding core_version_requirement: ^8 || ^9 to your info file and removing core: 8.x will be sufficient. See Create an Info File for a Module for details.

For Drupal 8.8 and above and Drupal 9 PROJECT/web/modules/dino_roar/dino_roar.info.yml:

name: Dino ROAR
type: module
description: "ROAR at you"
package: Sample
core_version_requirement: ^8 || ^9