Creating a custom module with routing and menu items in Drupal 8

Drupal 8 changes quite a bit when you go to create a custom module. This post will take us through setting up a module and adding a route and menu item. We are going to create a module that lets us track whether Game of Thrones characters are alive or dead, because it’s damn hard to keep track of them all!

1. Create a new directory for the module under the ‘modules’ directory. This is now in docroot, previously it was under sites/all. From docroot:

2. Inside the module directory, create a file called thrones.info.yml. This is a YAML file, which is a data markup language that has been selected for use throughout Drupal 8. You can read more about it at http://en.wikipedia.org/wiki/YAML.

The yaml file should contain something like:

Now create thrones.module and add the following:

Great! A fully functional Drupal 8 module! Head to the Extend page and enable it. It will be under the Other category, or use the new search box to quickly locate it.

Head back to thrones.module and lets add the menu item. To do this we will need several things: a YAML file containing the routes (linking a URL to a controller), a hook_menu() to add the menu item and a controller class (very scary!).

Add the following to thrones.module:

Now create ‘thrones.routing.yml’ and add the following:

Lastly, you need to create the controller. From the module’s root directory create the controller’s directory:

Inside the controller directory create the file ‘ThronesController.php’. This will contain your controller class, which should look like this:

Now, head to admin/config/development/performance and clear the cache. Now navigate to admin/config/thrones and bask in the glory!

The Change record for the New Symfony Based Routing System has heaps more information on routes and what-not.

I’ll take this module further in future posts.

 

 

 

DrupalCon Sydney 2013

DrupalCon Sydney went down last weekend, and it was special for a few reasons. It was the first DrupalCon in the southern hemisphere, the first outside of the US and Europe, and  my first national Drupal event.

There have been two previous Australia wide Drupal camps, Drupal Down Under 2011 and  2012. I had tickets and flights for the former, but broke my ankle at a bucks do shortly before. For the latter I was busy touring India. So this was my first opportunity to see how amazing the Drupal community is in the real life. And trust me, it was awesome.

I went there looking for a mentor to help me delve further into core development. Instead I met a bunch of inspiring folks and, well, got drunk with them. Great fun, would do again.

It all went down on Sydney’s Coogee beach, hosted at the Crowne Plaza Hotel. Great venue that managed to supply mostly-fast wifi for 400+ Drupal geeks.

Dries’ keynote was first up. He started out discussing the difference Drupal has made in the world, mentioning the Sandy hurricane response website, the ALRC website where citizens can review upcoming laws and the Egypt Independent News websites role during the Arab Spriong. The point being, we have come this far, where next?

Following on, he outlined the various Drupal 8 initiatives and the progress they have been making – especially in an authoring experience direction. This section ended with a roadmap to the D8 release and an emphasis on getting things ready for the upcoming feature freeze (2 days from the time of writing!).

Next was a discourse on Drupal in the enterprise, and the things these organisations need to manage – content, community and commerce – and how Drupal is well placed to handle all three. This led into the concept of web experience management(WEM) which says that basically all business websites perform the same functions – attract, engage, influence, convert and retain.

He had a great diagram showing the various components of WEM, and how there was opportunity for the Drupal community to build businesses around each component.

Then the call to action went out – we need larger Drupal agencies that can work with global companies, we need more startups and we need to “embrace the elephants”. More than anything we need more talent, but I think everyone working with Drupal is aware of that.

Here’s a quick run down of sessions that stood out to me on the Thursday:

  • Drupal 8 Web Services with Moshe Weitzman – Services module is committed to core. You can enable the module, select entities and bundles to expose, then start writing your client application, such as a mobile app. The service is RESTful and can return XML and JSON-LD. Authentication relies on Drupal authentication at the moment, but they want to add HTTP authentication. Lots of interesting use cases like apps, integration with backbone.js and a large role in Drupal 8’s in-place editing functionality. Content sharing and content staging are made simpler as well.
  • Symfony Components: A Travel Guide with Piers Warmers -Drupal 8 is replacing a bunch of code with Symfony components, and I’ve been trying to get my head around the changes. This talk helped a lot with that. Topics covered include PSR-0, Composer and Packagist, Doctrine, Guzzle, Assetic and Twig. In summing up he mentioned that it would be really cool if Drupal could start contributing packages back to Packagist. The thought of abstracting and decoupling something like FormAPI scared the crap out of me!
  • Performance Tough Love with Mark Sonnabaum – This was an interesting Q&A session  on performance and how general strategies apply to Drupal. The most important thing I got out of it was the importance of profiling code in diagnosing performance issues. Mark posted up a link to a gist on github telling people how to setup xhprof, a PHP profiler developed at Facebook. I forked his gist and updated it with detailed instructions for setting up xhprof with Ubuntu 12.10.

Friday I went to all the sessions in the Core Conversations Summit track.

Firstly webchick took us through upgrading the Drupal 7 ‘Pants’ module to Drupal 8, live on stage. Many pants related LOLs were had. Upgrading blocks was particularly eye-opening. Blocks are now defined using the new Plugins system which looks a lot more complicated, but I guess its just a matter of getting used to it. Symfony Routing and annotations are a bit trippy too 🙂

The remainder of the Summit was discussion and Q&A with the Core Initiative leads, some of whom were dialed in on via a Google Hangout. This was all super exciting, D8 is going to be a mad release!

The final night was Trivia night, and the WA team started off well but fell apart by the end, unfortunately. Some of the questions were pretty damn hard. It’s a bit blurry from then on out, I know I ended up discussing T1 Calculators, first programming experiences and US gun politics until around 4am when we ended up sitting on Coogee beach eating Maccas. Great night.

Next day was a total wipe, the best we could think to do was head to the airconditioning in the Airport and chill. Took a few days to recover from the non-stop pace of Drupalcon, but I can’t wait for the next one. Bring on DrupalSouth Wellington!

 

 

 

Dependency Injection and Drupal 8

Drupal is changing a lot in 8.x, and one of those major changes is adding the Drupal Dependency Container. What is that exactly?

Explain Yourself

  • Dependency injection is a design pattern used to dynamically load service objects, such as a mail delivery service.
  • Normally an object decides what service classes it will use – it will instantiate an object of a given class, then use it. In dependency injection the object will call the injection container which will provide it suitable classes depending on runtime configuration.
  • Sometimes called ‘Inversion of control’
  • The injector is often called a container.

Why all the fuss?

  • Allows selection from multiple potential interfaces at runtime
  • Creates highly pluggable systems – easily switch out caching backends for example.
  • Great for testing – no need to bootstrap or live connections to external services, just give the subsystem a stub implementation. Components can be tested in isolation.

How does it work?

  • Specify the interface for the dependency
  • Let the container object select the implementation

Types of Injection

  • Constructor injection – most common, pass in service object via constructor.
  • Setter injection – good for optional dependencies
  • Property injection – set public attributes directly.

Drupal’s DIC Implementation

One of the first things drupal_handle_request() does is instantiate an object of class DrupalKernel, which is extended from Symfony’s HttpKernel class Kernel.

Getting a service from the container:

To create a new service we implement the Bundle class:

You can see the core implementation of this in lib/Drupal/Core/CoreBundle.php. Some of the services registered include:

  • Configuration system
  • Database connection
  • Queue system
  • Path alias manager
  • Entity manager
  • HTTP Kernel
  • Language manager
  • Twig

Thats a pretty basic overview of Dependency Injection and how it is implemented in Drupal. Lots more information can be found in the links below.

References