18.11.2015 Views

Beginning Drupal 8

Todd Tomlinson - Beginning Drupal 8 (The Expert's Voice in Drupal) - 2015

Todd Tomlinson - Beginning Drupal 8 (The Expert's Voice in Drupal) - 2015

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 12 ■ Anatomy of a Module<br />

Step 5: Create the Module’s Controller<br />

<strong>Drupal</strong> 8 follows Symfony’s and PHP 5’s object orientation approach. One of the key concepts that <strong>Drupal</strong><br />

8 has adopted is a standard called PSR-4, which defines how code is loaded into memory. One of the issues<br />

with previous versions of <strong>Drupal</strong> is that a lot of code is loaded into memory when it doesn’t need to be there.<br />

PSR-4 solves that issue, and one of the enablers is something called namespaces. In our routing file, the value<br />

associated with _content starts with \<strong>Drupal</strong>\hello\Controller, which is a namespace. PSR-4 defines<br />

that a namespace maps directly to the file structure of your application. Symfony requires that all of our<br />

namespace directories reside within a directory named src, which resides in the root directory<br />

of our module.<br />

So let’s get busy and create the directories where the next component of our module will reside, the<br />

controller. While in the root directory of our hello module, create a new directory named src, and within<br />

the src directory, create a new directory named Controller. Within the Controller directory, we’re now ready<br />

to create the controller for our application, the “traffic cop” of our application. In your favorite text editor,<br />

create a file named HelloController.php. The contents of our controller should be<br />

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!