Mastering Drupal 8 - Chaz Chumley - E-Book

Mastering Drupal 8 E-Book

Chaz Chumley

0,0
42,22 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

Mastering Drupal can lead to a mighty website - discover what Drupal 8 can really do with hidden techniques, best practices, and more!

Key Features



  • The most up-to-date advanced practical guide on Drupal 8 with an in-depth look at all the advanced new features such as authoring, HTML markup, built-in web services, and more
  • If you are looking to dive deep into Drupal 8 and create industry-standard web apps, then this is the ideal book for you
  • All the code and examples are explained in great detail to help you in the development process

Book Description



Drupal is an open source content management system trusted by governments and organizations around the globe to run their websites. It brings with it extensive content authoring tools, reliable performance, and a proven track record of security. The community of more than 1,000,000 developers, designers, editors, and others have developed and maintained a wealth of modules, themes, and other add-ons to help you build a dynamic web experience.

Drupal 8 is the latest release of the Drupal built on the Symfony2 framework. This is the largest change to the Drupal project in its history. The entire API of Drupal has been rebuilt using Symfony and everything from the administrative UI to themes to custom module development has been affected.

This book will cover everything you need to plan and build a complete website using Drupal 8. It will provide a clear and concise walkthrough of the more than 200 new features and improvements introduced in Drupal core. In this book, you will learn advanced site building techniques, create and modify themes using Twig, create custom modules using the new Drupal API, explore the new REST and Multilingual functionality, import, and export Configuration, and learn how to migrate from earlier versions of Drupal.

What you will learn



  • Discover how to better manage content using custom blocks and views
  • Display content in multiple ways, taking advantage of display modes
  • Create custom modules with YAML and Symfony 2
  • Easily translate content using the new multilingual capabilities
  • Use RESTful services and JavaScript frameworks to build headless websites
  • Manage Drupal configuration from one server to another easily

Who this book is for



This book is ideally suited to web developers, designers, and web administrators who want to dive deep into Drupal. Previous experience with Drupal is a must to unleash the full potential of this book.

Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:

EPUB

Seitenzahl: 377

Veröffentlichungsjahr: 2017

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Mastering Drupal 8

 

 

 

 

 

 

 

 

 

 

A comprehensive and advanced practical guide to master Drupal 8

 

 

 

 

 

 

 

 

 

 

Chaz Chumley
William Hurley

BIRMINGHAM - MUMBAI

< html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">

Mastering Drupal 8

 

 

Copyright © 2017 Packt Publishing

 

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the authors, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

First published: July 2017

Production reference: 1250717

Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham
B3 2PB, UK.

ISBN 978-1-78588-597-6

www.packtpub.com

Credits

Authors

 

Chaz Chumley

William Hurley

Copy Editor

 

Safis Editing

Reviewer

 

Michael Drayer

Project Coordinator

 

Ulhas Kambali

Commissioning Editor

 

Amarabha Banerjee

Proofreader

 

Safis Editing

Acquisition Editor

 

Anurag Banerjee

Indexer

 

Mariammal Chettiyar

Content Development Editor

 

Onkar Wani

Graphics

 

Abhinash Sahu

Technical Editor

 

Shweta Jadhav

Production Coordinator

 

Shraddha Falebhai

About the Author

Chaz Chumley, ever since Chaz can remember, he has been picking up a crayon, a pencil, a pen, or a computer, whether to draw a picture, write a poem, share an article, or develop the next great website. Looking back at these qualities, it's the reason he chose to use those passions to give back to the open source community. His journey has opened doors to great experiences as a consultant, instructor, trainer, author, web developer, technical architect, Drupalist, and most importantly, a father. However, he could be none of these without first being a student and learning from life, love, and a passion for education, community development, and of course, science and technology.

The sum of these things has allowed Chaz to share his experiences as an active member of the Drupal community, having participated in developing Lynda.com Drupal training videos, authoring multiple Drupal books for Packt Publishing, and giving back his knowledge by contributing numerous articles, training, and presentations at Design4Drupal, BadCamp, DrupalGovCon, and DrupalCon, all the while bringing top-notch Drupal expertise to his clients' work.

However, his greatest journey is still in front of him as he continues to learn new creative ways to architect open source websites, write about the next best things, and laugh with his colleagues along the way.

Acknowledgments

Seeing that this is the second book I have now written; the process is becoming much easier. I still make mistakes, correct them, and then make some more. However, I welcome the feedback that I get from my family, friends, and colleagues who have helped review it all along the way. I am very surprised how fast Drupal 8 has moved and improved along the way, all for the better. During this journey, I must reflect on the one person who instilled in me my work ethic, my father; he was a tough man, but I respected him. He has since passed away and while I know he shines down on me, I can still hear him telling me to push myself, love my family, and respect everyone. While I did not get a chance to say goodbye to him, I know he knows how much I love him. Speaking of family, I have been blessed with two great moms, an awesome brother Josh, and a beautiful sister Carly. However, the most important person to thank is my wife, Rebecca. She s been my biggest fan and without her, none of this would be possible. She kept me sane on long weekends and late nights of writing. She made me laugh when I wanted to scream or cry. She took me on long walks, longer hikes in the Appalachian Trail, and even to one of the Seven Wonders of the World, Machu Picchu. However, after 25 years of marriage, I still think you re the greatest wonder in the world. Finally, a huge thank you to my colleagues at Forum One: rock star developers, awe-inspiring designers, breathtaking UX, and amazing marketing. Hey Drupal! Come for the code, stay for the community.

About the Author

William Hurley, is the chief technology officer at Forum One. He is responsible for partnering with clients to develop technical recommendations that truly serve their organizational needs. He received a bachelor's degree from George Mason University's department of computer science. He's also a culinary aficionado, and he has a notably soft spot for curry. William has been developing for the web since 1997 using PHP, Java, Adobe Flex, JavaScript, and ColdFusion, and brings a breadth of technical expertise to clients' most difficult digital dilemmas.

William is an active member of the Drupal community. He has contributed more than 10 modules, along with patches to Drupal core and other contributed modules. With close to a hundred commits, William does his best to give back to the Drupal community.

I would like to thank Meredith Hurley, my wife, for helping me keep writing and putting up with me when I did just that.

About the Reviewer

Michael Drayer has been working with Drupal websites for 5 years, and has been building them for 3 years. He is a developer at Forum One.

Customer Feedback

Thanks for purchasing this Packt book. At Packt, quality is at the heart of our editorial process. To help us improve, please leave us an honest review on this book's Amazon page at http://www.amazon.in/Mastering-Drupal-8-Chaz-Chumley/dp/1785885979.

If you'd like to join our team of regular reviewers, you can email us at [email protected]. We award our regular reviewers with free eBooks and videos in exchange for their valuable feedback. Help us be relentless in improving our products!

www.PacktPub.com

For support files and downloads related to your book, please visit www.PacktPub.com.

Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [email protected] for more details.

At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.

https://www.packtpub.com/mapt

Get the most in-demand software skills with Mapt. Mapt gives you full access to all Packt books and video courses, as well as industry-leading tools to help you plan your personal development and advance your career.

Why subscribe?

Fully searchable across every book published by Packt

Copy and paste, print, and bookmark content

On demand and accessible via a web browser

Table of Contents

Preface

What this book covers

What you need for this book

Who this book is for

Conventions

Reader feedback

Customer support

Downloading the example code

Downloading the color images of this book

Errata

Piracy

Questions

Developer Workflow

Deciding on a local AMP stack

The role of Composer

Installing Composer locally

Installing Composer globally

Using Composer to create a Drupal project

Speeding up tasks using Drush

Using Drush wrapper

Installing Drush globally

Using Drush to create a Drupal project

A quick look at Drupal Console

Accessing Drupal Console locally

Installing Drupal using Drupal Console

Installing Drupal Console globally

Running a built-in PHP web server

Using Git to manage source code

Installing Git

Configuring Git

Creating a remote repository

Setting up a local repository

Tracking and committing files with Git

Adding a remote origin

Pushing files to the remote repository

Virtualizing an environment

Using Drupal VM as a web starter

Summary

Site Configuration

Assumptions

Exploring Drupal's interface

Managing Drupal

Basic site settings

SITE DETAILS

FRONT PAGE

ERROR PAGES

Performance

Clearing cache

Using Drush to clear cache

Using Drupal Console to clear the cache

Configuration overrides

Using Drush to manage configuration

Listing configuration variables

Retrieving specific variables

Setting configuration variables

Using Drupal Console to manage configuration

Listing configuration variables

Retrieving specific variables

Setting configuration variables

Working with the File system

Managing file paths

Regional settings

Date and time formats

Adding new date formats

Summary

Managing Users, Roles, and Permissions

Assumptions

Exploring People

Managing roles and permissions

What is a role?

Creating a role

Reordering roles

Editing a role

Setting permissions

Working with users

Adding a user

Bulk updating users

Configuring Account settings

CONTACT SETTINGS

ADMINISTRATOR ROLE

REGISTRATION AND CANCELLATION

Managing user fields

Adding fields

Managing form display

Using Drush to manage roles

Listing roles

Creating roles

Deleting roles

Listing permissions

Adding permissions

Removing permissions

Using Drush to manage users

Displaying user information

Assigning roles

Removing roles

Blocking a user

Unblocking a user

Creating user accounts

Cancelling user account

Resetting passwords

Creating a one-time login

Summary

Content Types, Taxonomy, and Comment Types

Assumptions

Exploring Content types

Submission form settings

Preview before submitting

Publishing options

Managing revisions

Reverting content

Display settings

Menu settings

Managing fields

Field settings

Creating custom content types

Managing fields using the Field UI

Deleting fields

Adding new fields

Author field

Teaser field

Content field

Featured Image field

Taxonomy, Vocabularies, and Terms

Adding a vocabulary

Adding terms

Adding a Taxonomy field

Working with Comment types

Adding a Comment type

Adding Comment type field

Working with form and content display

Reordering fields

Modifying Field Widgets

Disabling fields

Using Drupal console to generate dummy content

Creating vocabularies

Creating comments

Creating nodes

Summary

Working with Blocks

Assumptions

Block layout and Regions

Demonstrating block regions

Placing blocks into regions

Block configuration, settings, and visibility

Managing the block title

Using the Contextual menu

Managing visibility settings

Content types restriction

Page restriction

Role restriction

Creating a custom block

Defining the Region

Exploring the Custom block library

Editing custom blocks

Managing block types

Adding fields to blocks

Manage form display

Reordering fields

Modifying field formats

Managing display

Using the Place block interface

Deleting Blocks from Block layout

Summary

Content Authoring, HTML5, and Media

Assumptions

Responsive admin

CKEditor and text formats

Text formats

Toolbar configuration

CKEditor plugin settings and filters

Enabled filters

Filter processing order

Filter settings

Working with images

Image alignment

Image captions

Managing displays

Reordering fields

Controlling labels

Using Field Formatters

Formatting a date field

Managing the Teaser display

Using Better preview

Custom Display settings

Adding a view mode

Image styles

Configuring image styles

Adding image styles

Quick edit

Summary

Understanding Views

Customized lists of contents

View displays

Creating view pages and blocks

Block display

Working with filter criteria and sorting

Rearrange filter criteria

Expose filters

Formatting rows

Row styling

Fields

Content

Field formatting

View formats

Unformatted list

Grid

HTML List

Table

Using advanced features

Relationships

Contextual filters

Display all results for the specified field

Provide a default value

Hide view

Display a summary

Display contents of "No results found"

Display "Access Denied"

Query aggregation

AJAX

Summary

Theming Essentials

Assumptions

What is a theme?

Exploring the Appearance interface

Drupal's core themes

Bartik

Seven

Stark

Classy

Theme states

Installed themes

Uninstalled themes

Default theme

Installing and uninstalling themes

Step one - installing a theme

Step two - uninstalling a theme

Theme settings

Toggling the display of page elements

Logo image settings

Favicon settings

Theme-specific settings

Using prebuilt themes

Folder structure and naming conventions

Managing configuration in Drupal 8

Reviewing the new info.yml file

Metadata

Libraries

Defining a library

Overriding libraries

Extending libraries

Attaching a library

Using Twig to attach a library

Using the preprocess functions to attach a library

Regions

Adding assets to CKEditor

The role of templates in Drupal

How templates work

Where to find templates

Creating a simple theme

Step one - creating a new folder

Step two - create an info file

Step three - create a libraries file

Step four - copy core templates

Step five - include a screenshot

Step six - installing our theme

Summary

Working with Twig

Assumptions

Configuring settings.local.php

Enabling local development services

Disabling render and page cache

Disabling test modules and themes

Enabling Twig debug

Twig fundamentals

Commenting variables

Setting variables

Printing variables

Dumping variables

Filters

Control structures

Functions

Template variables

The role of the theme file in Drupal

Preprocessors and hooks

Working with libraries

Adding assets

Creating a library reference

Including our library

Introducing web fonts

Creating our Jumbotron Block

Step one - Creating a custom block

Step two - Adding a new Jumbotron block

Step three - Placing the Jumbotron block

Page template

Node template

Block template

Field templates

Summary

Extending Drupal

Using Drush

Using Composer

Creating a new module

Understanding configuration and plugins

YAML

Plugins

Annotations

Anatomy of a plugin manager

Working with dependency injection

Services

Creating your own service

Services definition file

abstract

alias

calls

configurator

factory

parent

properties

public

scope

tags

Service implementation

Using your service

Permissions

Routing and menus

Basic routing

Display methods

_form

_entity_view

_entity_list

_entity_form

Handling arguments

Requirements checking

Route matching

_module_dependencies

_method

Parameter matching

Access tests

_permission

_role

_access

_entity_access

_csrf_token

Dynamic routes

Menu links

Local tasks

Local actions

Contextual links

Events and hooks

Using the EventDispatcher

Summary

Working with Forms and the Form API

Creating and managing forms

Creating a new form

Using FormState

Other form types

Exploring the Form API

New Form API types

Color

Details

Dropbutton

HTML tag

Language select

Link

More link

Pager

Path element

Table select

URL

Using AJAX

Summary

RESTful Services

Overview of REST

REST in Drupal 8

HTTP verbs

HAL JSON

Enabling core modules and customizing permissions

Exposing content using Views

Using RESTful endpoints

Displaying content

Unsafe methods and CSRF protection

Creating content

Updating content

Deleting content

Authenticating an application as a Drupal user

Core methods

Contrib methods

Creating REST resources

Using parameters

Using the current user

Summary

Multilingual Capabilities

Enabling core multilingual modules

Language

Interface Translation

Content Translation

Configuration Translation

Installing and configuring languages

Adding language detection

Account administration pages

URL

Session

User

Browser

Selected language

Content language detection

Working with language switching blocks

Translating content

Translating the Drupal admin UI

Using the multilingual API

PHP code

JavaScript

YML files

Annotations

Twig templates

Summary

Configuration Management

Configuration Management files

File format

Schema

Scalar values

Mapping

Sequence

Reusable types

Dynamic type references

Override system

Differences between configuration and state

Using the Config object

Configuration interface

Synchronize configuration

Exporting single configuration

Importing single configuration

Exporting whole site configuration

Importing whole site configuration

Configuration workflow with Drush

Configuration and multilingual sites

Configuration forms

Configuration translation

User interface translation

Summary

Site Migration

Enabling core modules to migrate content

Using Drupal 8's Migrate to handle migrations

Extending migrations with contributed modules

Building a migration process

Creating a migration source

Creating a migration processor

Using Drush to manage migrations

Summary

Debugging and Profiling

Enabling core debugging

Disabling caching

Enabling Twig debugging

Debugging cache performance

Working with Devel and Kint

Installing the Devel module

Printing variables

Printing backtrace

Using the Web Profiler

Installing the Web Profiler module

Request information

Processing timeline

Performance timing

Debugging queries

Debugging Views

Summary

Preface

Drupal is an open source content management system trusted by governments and organizations around the globe to run their websites. It brings with it extensive content authoring tools, reliable performance, and a proven track record of security. The community of more than 1,000,000 developers, designers, editors, and others have developed and maintain a wealth of modules, themes, and other add-ons to help you build a dynamic web experience.

Drupal 8 is the latest release of Drupal built on the Symfony2 framework. This is the largest change to the Drupal project in its history. The entire API of Drupal has been re-built using Symfony, and everything from the administrative UI to themes to custom module development has been affected.

This book will cover everything you need to plan and build a complete website using Drupal 8. It will provide a clear and concise walkthrough of the more than 200 new features and improvements introduced in Drupal core. You will learn advanced site building techniques, how to create and modify themes using Twig, create custom modules using the new Drupal API, explore the new REST and multilingual functionality, import and export Configuration, and how to migrate from the earlier versions of Drupal.

What this book covers

Chapter 1,Developer Workflow, walks you through setting up a development workflow. You will learn how to install Composer, Drush, and Drupal console to easily work with Drupal 8. We will also discuss the Git workflow and how it plays an important role in Mastering Drupal 8.

Chapter 2, Site Configuration, says that site configuration is probably one of the most important tasks any developer will need to perform. So, to ensure that you have a well-established baseline, we will walk through the basic site settings, performance, configuration overrides, and how to use Drush to speed up your workflow.

Chapter 3, Managing Users, Roles, and Permissions, provides us with the experience to configure account settings, which ensure that your next Drupal site is safe and secure. We will work with users, manage roles and permissions, and look at how Drush can help manage it all from the command line.

Chapter 4, Content Types, Taxonomy, and Comment Types, looks at one of the most powerful capabilities of Drupal to allow for the creation of custom content types. You will learn how to manage fields, work with Taxonomy, vocabularies, and terms to allow for tagging content. We will also look at Drupal Console, another command-line tool to speed up generating content.

Chapter 5, Working with Blocks, covers the basics of Blocks and Regions. We will take a deep dive into block configuration, custom blocks, and how to best manage block settings and visibility. Join us as we also look at some experimental modules that allow for placing blocks easily.

Chapter 6, Content Authoring, HTML5, and Media, is one of the greatest improvements to Drupal 8. In this chapter, we will learn how to work with responsive admin, manage content creation with CKEditor, text formats, and how to use image styles to display various media.

Chapter 7, Understanding Views, will explain how to use views to create lists of content to be displayed throughout the site. This includes using filters, relationships, and contextual filters to build new listing pages and blocks.

Chapter 8, Theming Essentials, explores the appearance interface and the core default themes shipped with Drupal 8. You will quickly get a better understanding of what makes up a theme, how to best manage themes, and best practices for setting up your theme's structure.

Chapter 9, Working with Twig, takes us through setting up our local development environment for theming and enabling Twig debug. We will then take a close look at Twig syntax, filters, control structures, and functions when working with templates. Finally, we will look at how to manage assets and preprocess variables.

Chapter 10, Extending Drupal, Looks at how, with the adoption of Symfony to power Drupal 8, writing of custom modules, which has changed dramatically. In this chapter, we will learn about dependency injection, how to use the new routing and menu system, adding permissions, and using events and hooks.

Chapter 11, Working with Forms and the Form API, will introduce the Form API. We will learn about all the new elements available in Drupal 8, and how to create new forms to capture user input and use it in your custom modules.

Chapter 12, RESTful Services, teaches the new REST API in Drupal 8. We will learn how to expose content via the Views REST plugin, as well as how to write our own REST API resource to provide custom functionality.

Chapter 13, Multilingual Capabilities, walks us through Drupal 8 and all the tools necessary to create a fully translated and localized site out of the box. In this chapter, we will learn how to enable and configure the appropriate modules, translate content, and create multi-lingual configurations.

Chapter 14, Configuration Management, Introduces the new configuration management system in Drupal 8. We will learn how to export configuration from one environment and import it into another, as well as how to use it in our own custom modules.

Chapter 15, Site Migration, explains how to migrate content from the previous versions of Drupal or other systems into a new Drupal 8 site. We will learn how to configure the migration process and how to modify and enhance the data before its saved.

Chapter 16, Debugging and Profiling, says that developing a complex Drupal site requires us to peek inside and see whats going on while its running. This chapter will describe how we can easily debug issues and profile our site to understand how each layer is performing.

What you need for this book

To follow along with this book, you need an installation of Drupal 8, preferably in a local development environment located on a Windows, Mac, or Linux-based computer. Documentation regarding setting up a local development environment is covered in Chapter 1, Developer Workflow, and can also be found at https://www.drupal.org/setting-up-development-environment.

To follow along with each lesson, you will need a text editor or IDE. To see a list of software to consider using when developing in Drupal 8, you can refer to https://www.drupal.org/node/147789.

Finally, you will need to have administrative access to your Windows, Mac, or Linux-based computer, with the ability to run a Terminal window that will allow you to execute various commands and install various items.

Who this book is for

This book is ideally suited to web developers, designers, and web administrators who want to dive deep into Drupal. Previous experience with Drupal is a must to unleash the full potential of this book.

Conventions

In this book, you will find several text styles that distinguish between different kinds of information. Here are some examples of these styles and an explanation of their meaning.

Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and terminal commands as follows: "So if we changed the route URL to mastering_drupal_8/test/{message}, we would change the controller function to:"

A block of code is set as follows:

name: Testtype: themedescription: A test theme.core: 8.xlibraries: - test/globalregions: header: Header content: Content # the content region is required sidebar_first: 'Sidebar first' footer: Footer

Any command-line input or output is written as follows:

# composer create-project drupal/drupal

New terms and important words are shown in bold. Words that you see on the screen, for example, in menus or dialog boxes, appear in the text like this: "Clicking the Next button moves you to the next screen."

Warnings or important notes appear like this.
Tips and tricks appear like this.

Reader feedback

Feedback from our readers is always welcome. Let us know what you think about this book-what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of.

To send us general feedback, simply email [email protected], and mention the book's title in the subject of your message.

If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.

Customer support

Now that you are the proud owner of a Packt book, we have several things to help you to get the most from your purchase. You can contact the authors at https://forumone.com/team/william-hurley or https://forumone.com/team/chaz-chumley if you are facing a problem with any aspect of this book.

Downloading the example code

You can download the example code files for this book from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files emailed directly to you.

You can download the code files by following these steps:

Log in or register to our website using your email address and password.

Hover the mouse pointer on the

SUPPORT

tab at the top.

Click on

Code Downloads & Errata

.

Enter the name of the book in the

Search

box.

Select the book for which you're looking to download the code files.

Choose from the drop-down menu where you purchased this book from.

Click on

Code Download

.

Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:

WinRAR / 7-Zip for Windows

Zipeg / iZip / UnRarX for Mac

7-Zip / PeaZip for Linux

The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/Mastering-Drupal-8. We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

Downloading the color images of this book

We also provide you with a PDF file that has color images of the screenshots/diagrams used in this book. The color images will help you better understand the changes in the output. You can download this file from https://www.packtpub.com/sites/default/files/downloads/MasteringDrupal8_ColorImages.pdf.

Errata

Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books-maybe a mistake in the text or the code-we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.

To view the previously submitted errata, go to https://www.packtpub.com/books/content/supportand enter the name of the book in the search field. The required information will appear under the Errata section.

Piracy

Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy. Please contact us at [email protected] with a link to the suspected pirated material. We appreciate your help in protecting our authors and our ability to bring you valuable content.

Questions

If you have a problem with any aspect of this book, you can contact us at [email protected], and we will do our best to address the problem.

Developer Workflow

In order to fully take advantage of Drupal 8, it helps to have an established developer workflow. This can range from having a local web server to using a fully integrated, virtualized AMP (Apache, MySQL, PHP) stack that mimics the development, staging, and production servers that one may need to deploy Drupal. It also helps to establish a set of best practices to follow when it comes to installing, managing, and working with Drupal 8 on a project-by-project basis. While there are various tools to choose from, we will look at some of the most common ones available to us, including Composer, Drush, DrupalConsole, and Git.

The deeper we dive into mastering Drupal 8, the more vital it becomes to learn command-line interfaces, such as Composer, Drush, Git, and Drupal Console. These require the use of a Terminal window and a level of comfort when working with the command line. While we will not be covering the basics of Windows or Unix shell, we will explain what each command does and how each tool speeds up our developer workflow.

In this chapter, we will be covering the basics of how to use each of these tools to install, extend, and manage a typical Drupal 8 developer workflow, including the following:

Deciding on a local AMP stack

The role of Composer

Speeding up tasks using Drush

A quick look at Drupal Console

Using Git to manage source code

Virtualizing an environment

Deciding on a local AMP stack

A developer workflow begins with having an AMP (Apache, MySQL, PHP) stack installed and configured on a Windows, OS X, or *nix based machine. Depending on the operating system, there are a lot of different methods that one can use to set up an ideal environment. However, when it comes down to choices, there are only three:

Native AMP stack

: This option refers to systems that generally either come preconfigured with Apache, MySQL, and PHP, or have a generally easy installation path to download and configure these three requirements. There are plenty of great tutorials on how to achieve this workflow, but this requires familiarity with the operating system.

Packaged AMP stack

: This option refers to third-party solutions, such as MAMP(

https://www.mamp.info/en/

)

, WAMP(

http://www.wampserver.com/en/

), or Acquia Dev Desktop(

https://dev.acquia.com/downloads

). These solutions come with an installer that generally works on Windows and OS X, and is a self-contained AMP stack allowing for general web server development. Out of these three, only Acquia Dev Desktop is Drupal specific.

Virtual machine

(

VM

): This option is often the best solution as it closely represents the actual development, staging, and production web servers. However, this can also be the most complex to initially set up and requires some knowledge of how to configure specific parts of the AMP stack. There are a few well-documented VMs available that can help reduce the experience needed. Two great virtual machines to look at are Drupal VM(

https://www.drupalvm.com/

) and

Vagrant Drupal Development

(

VDD

)(

https://www.drupal.org/project/vdd

).

In the end, my recommendation is to choose an environment that is flexible enough to quickly install, set up, and configure Drupal instances. The preceding choices are all good to start with, and by no means is any single solution a bad choice.

If you are a single person developer, a packaged AMP stack such as MAMP may be the perfect choice. However, if you are in a team environment, I would strongly recommend one of the previously mentioned VM options or consider creating your own VM environment that can be distributed to your team.

We will discuss virtualized environments in more detail, but, before we do, we need to have a basic understanding of how to work with three very important command-line interfaces: Composer, Drush, and Drupal Console.

The role of Composer

Drupal 8 and each minor version introduces new features and functionality: everything from moving the most commonly used third-party modules into its core to the introduction of an object-oriented PHP framework. These improvements also introduced the Symfony framework that brings in the ability to use a dependency management tool called Composer.

Composer (https://getcomposer.org/) is a dependency manager for PHP that allows us to perform a multitude of tasks: everything from creating a Drupal project to declaring libraries and even installing contributed modules, just to name a few. The advantage of using Composer is that it allows us to quickly install and update dependencies by simply running a few commands. These configurations are then stored within a composer.json file that can be shared with other developers to quickly set up identical Drupal instances.

If you are new to Composer, let's take a moment to discuss how to go about installing Composer for the first time within a local environment.

Installing Composer locally

Composer can be installed on Windows, Linux, Unix, and OS X. For this example, we will be following the install found at https://getcomposer.org/download/. Ensure that you take a look at the Getting Started documentation that corresponds with your operating system.

Begin by opening a new Terminal window. By default, our Terminal window should place us in the user directory. We can then continue by executing the following four commands:

Download Composer installer to the local directory:

php -r "copy('https://getcomposer.org/installer', 'composer-

setup.php');"

Verify the installer:

Since Composer versions are often updated, it is important to refer to the date on the Download Composer page to ensure that the preceding hash file is the most current one.

Run the installer:

php composer-setup.php

Remove the installer:

php -r "unlink('composer-setup.php');"

Composer is now installed locally, and we can verify this by executing the following command within a Terminal window:

php composer.phar

Composer should now present us with a list of the available commands:

The challenge with having Composer installed locally is that it restricts us from using it outside the current user directory. In most cases, we will be creating projects outside of our user directory, so having the ability to globally use Composer quickly becomes a necessity.

Installing Composer globally

Moving the composer.phar file from its current location to a global directory can be achieved by executing the following command within a Terminal window:

mv composer.phar /usr/local/bin/composer

We can now execute Composer commands globally by typing composer in the Terminal window.

Using Composer to create a Drupal project

One of the most common uses for Composer is the ability to create a PHP project. The create-project command takes several arguments, including the type of PHP project we want to build, the location where we want to install the project, and, optionally, the package version. Using this command, we no longer need to manually download Drupal and extract the contents into an install directory. We can speed up the entire process using one simple command.

Begin by opening a Terminal window and navigating to the folder where we want to install Drupal. Next, we can use Composer to execute the following command:

composer create-project drupal-composer/drupal-project:8.x-dev mastering --stability dev --no-interaction

The create-project command tells Composer that we want to create a new Drupal project within a folder called mastering. We also tell Composer that we want the most stable development version. Once the command is executed, Composer locates the current version of Drupal and installs the project, along with any additional dependencies that it needs:

The Composer project template provides a kick-start for managing Drupal projects following best practice implementation. This includes installing both Drush and Drupal Console, which are command line tools we can use to work with Drupal outside of the typical user interface. The reason Drush and Drupal console are packaged with the Composer project is both to avoid dependency issues and to allow for different versions of these tools per project. We will explore Drush and Drupal Console in greater detail a little later.

Composer also scaffolds a new directory structure that warrants taking a moment to review:

The new directory structure places everything related to Drupal within the /web folder, including the core, modules, profiles, sites, and themes. Drush and Drupal Console along with any dependencies that Drupal needs get installed within the /vendor folder. The remaining two folders /drush and /scripts are utilized by Drush and Drupal 8 to help configure our project.

All the installation, configuration, and scaffolding that takes place is a result of the composer.json file that Composer uses to create a project. Often referred to as a package, the composer.json file allows us to distribute it to other computers, web servers, or team members to generate an identical Drupal 8 code base by simply executing, composer install.

We will be using Composer to manage every aspect of a Drupal project. This will include the ability to update Drupal core when new versions are available, install and update Modules that we may want to use to extend Drupal, and to add any additional configuration to manage installer paths and possibly patch modules. We will review these additional commands throughout the book.

For now, lets switch our focus to some of the command line tools that were installed with our Drupal project, beginning with Drush.

Speeding up tasks using Drush

Drush (http://www.drush.org/en/master/) is a command-line shell and Unix-scripting interface that allows us to interact with Drupal. Drush gives us the ability to use the command line to accomplish tasks quickly, without the need to rely on the Drupal admin UI. As part of the composer install, our project has the latest version of Drush installed automatically.

Executing a Drush command is typically as easy as typing the word drush within a Terminal window.

However, the challenge of having a per-project instance of Drush is in the way we are forced to currently execute Drush commands. Since the drush executable is located within the projects /vendor/bin/drush folder, if we are within the root of our project, we execute drush by entering the following within the Terminal window:

./vendor/bin/drush

The problem is the path can easily change; if, for instance, we are in the /web root, the same command would be:

../vendor/bin/drush

Notice the two dots indicating one must traverse up a level to locate the /vendor folder.

This is not ideal when we will be using Drush quite frequently to perform various tasks. We can resolve this in a couple of different ways.

Using Drush wrapper

The first is to use drush.wrapper located within the /vendor/drush/drush/examples folder. This file is a wrapper script that launches Drush within a project. If we open the file within an editor, we will see that it states we need to copy the file to our /web folder and rename it to drush.

Choosing to follow this method would then allow us from within the /web folder to execute drush commands by entering the following within our Terminal window:

./drush

This is a little better; however, this is not quite as nice as simply typing the word drush without the need to know how to run a script. We can accomplish this by globally installing Drush using Composer.

Installing Drush globally

Installing Drush globally varies based on the operating system or AMP stack, as there is a dependency on PHP 5.5.9 or higher. This dependency will be satisfied in most cases, but ensure that you verify the version of PHP that is available.

Begin by opening the Terminal window, changing into the user directory, and executing the following commands:

Verify that Composer is installed:

composer

Add Composer's bin directory to the system path:

export PATH="$HOME/.composer/vendor/bin:$PATH"

Install the latest stable release:

composer global require drush/drush

Verify that Drush works:

drush status

Now that Drush has been installed globally, we can easily ensure that we always have the latest version by running this:

composer global update

To get our first look at the available commands that Drush provides, we can execute the following:

drush

The list of Drush commands is quite long, but it does provide us with the ability to perform almost any action we may need when working on a Drupal project. Some simple commands that we will commonly use throughout the book are clearing cache, managing configurations, and even installing Drupal. For a list of all the various commands, we can browse Drush Commands at https://drushcommands.com/.

Using Drush to create a Drupal project

Some common uses of Drush are to download modules, themes, and even Drupal itself. The command to execute this task is drush dl. Since we previously installed Drush globally, we can change to a brand-new directory using the Terminal window, and download another copy of Drupal by executing the following command:

drush dl drupal

As we can see from the preceding screenshot, executing the command downloads the current version of Drupal. We can verify this by listing the contents of the current directory:

Now that we have a second copy of Drupal, we can use Drush to perform a quick install.

Note that, to use Drush to install Drupal without setting up or configuring an instance of an *AMP stack, we will need to at least have PHP 5.5.9 or higher installed.

Within a Terminal window, change into the drupal-8.x directory that Drush downloaded and execute the following command:

drush qd --use-existing --uri=http://localhost:8383 --profile=standard

This command tells Drush to perform a quick Drupal installation using the existing source files. Drupal will use the standard profile and, once the installation has completed, a PHP server will be started on localhost port 8383.

Ensure that you specify that you want to continue with the installation when prompted. Once the Drupal installation has finished, a browser window will open on the admin user page with the one-time login where we can then create a new password:

We will not be using this instance of Drupal, so we can terminate the PHP server that is currently running in the Terminal window by entering Ctrl + C on the keyboard.

Hopefully, we can begin to see how using Drush can speed up common tasks. Throughout each lesson, we will explore Drush in more detail and utilize additional commands. Now that we have a better understanding of Drush, it's time to take a look at another command-line tool that we can benefit from using when developing a Drupal website.

A quick look at Drupal Console

Drupal Console (https://drupalconsole.com/) is a new command-line tool that has been welcomed by the Drupal community. Like Drush, but in my opinion, much more powerful, Drupal Console allows us to perform site installs, manage configurations, create content, generate boilerplate code, and much more.

Accessing Drupal Console locally

As part of the original composer install of our Drupal project, Drupal console was installed. However, just like accessing Drush locally, we are faced with the same complexities of knowing the exact location of the Drupal console executable.

If we look within the /vendor/drupal/console/bin