Skip to content

Instantly share code, notes, and snippets.

@mparker17
Last active December 21, 2015 01:18
Show Gist options
  • Select an option

  • Save mparker17/6226149 to your computer and use it in GitHub Desktop.

Select an option

Save mparker17/6226149 to your computer and use it in GitHub Desktop.
Drupal 8 Training at @palantirnet

2013-08-13 13:00 — Notes from Drupal 8 Training @ Palantir.net

Overview

  • Drupal 8 for site builders
  • New concepts from PHP
  • Architecture overview
  • D8 building blocks
  • Testing

Understanding D8

  • Drupal 8 is a modern, PHP 5.3 application
    • We ported Drupal to a new language
  • The end of "Not Invented Here"
  • Playing nice with others
  • Concepts you need to understand:
    • Namespacing
      • All classes must be named like: \<Vendor Name>\(<Namcespace>)*\<Class Name>
      • Allows standard autoloading
    • Interfaces
      • Separate code design from code implementation
      • Allow objects to be mocked (testable)
      • Allow implementations to be swapped
      • Look at these first in Drupal core code
    • Annotations
      • Docblocks as class definitions
      • Parsed on execute
      • Largely replaces hook_*_info() blocks
      • Keeps definitions with the class that it defines
    • Plugins
      • Generic term for a "code model"
      • Basically, a standardized CTools plugin system
      • Autoloading
      • Encourages library code
      • See Views module in D7!
    • YAML
      • Generic, portable syntax for complex data
      • Core of the CMI, and a bunch of other places

Understanding the Web

  • HTTP Architecture: Request -> Your server -> Response
  • Symfony architecture: Request -> HttpKernel -> Response

Controllers

  • Should be very thin.
  • Request objects are passed in as a parameter named $request to a controller function
  • Note the order of the variables passed in doesn't really matter: as long as you name them the same as the routing.yml file.
  • Routes have:
    • machine names
    • patterns (begin with leading slash)
    • defaults (default values for parameters)
    • requirements (permissions, regular expressions to apply to parameters)
    • options

Assignment

  • Write 3 controllers:
    • Return "Hello world" as Drupal page body
    • Return "Hello world" as JSON response
    • Return "Hello %name" as Drupal page body, where name was passed in.
  • You can use https://github.com/palantirnet/hellodrupal (branch 01-initial) as a starting point.

Routing

  • Built on listeners
  • Using RouteEnhancers, you can wrap controller responses with other controller responses, allowing you to request a dialog version without the page stuff
  • Another listener is Access control:
    • Authentication = "Who are you?"
      • Note: $request->attributes->get('_account') replaces global $user
    • Authorization = "What are you allowed to do?"
      • Multiple "checkers" per route
      • Might apply or not
      • Can return:
        • static::ALLOW = This checker passes
        • static::DENY = This checker fails
        • static::KILL = Immediately deny access
      • _access_mode can be:
        • ANY = || = Allow if any checkers return TRUE
        • ALL = && = Allow only if all checkers return TRUE

Dependency injection

  • Dependency = "An object on which your object depends"
    • Always make your dependencies interfaces!
    • Sucks to wire it up though. See "Dependency Injection Container""
  • Service = "A generally-stateless "global" object"
    • There should only be one of these (i.e.: singleton), but the system should enforce that.
  • Dependency Injection Container" = "Place where you wire that stuff up in advance"
    • "Scariest possible name for an array of objects"
    • You'll almost never interact with it directly
    • Configure via YAML
    • Your classes should not know about it
  • Define services in modulename.services.yml.
    • Services have:
      • Machine name
      • Class that does the work
      • Optional list of arguments it needs to instantiate
      • Optional list of things that need to be called on it after it's created
  • System will detect circular dependencies and prevent you from setting it, at compile time.

2013-08-14 09:00 — Notes from Drupal 8 Training @ Palantir.net

Plugins

  • A narrow set of functionality
  • Allow us to customize and extend the original system, e.g.: graphics software processing image files
  • Similar to CTools
  • D8 - we wanted one plugin system that works universally in D8
  • Supports:
    • Plugin types
    • Plugin discovery
    • Plugin factory
  • Managers define and manage.
  • Some common types of plugins:
    • Blocks
    • Actions
    • Views
    • Entities
    • [field]Formatters
  • What is plugin discovery?
    • Find plugins, metadata
    • Parse it
    • Use annotations
  • When learning, start with actions or blocks. Check out the node module (core/modules/node/lib/Drupal/node/Plugin/...).
  • Tips:
    • id = machine name
    • Always use double-quotes
    • Strings must use quotes
    • Numbers and booleans must NOT use quotes
    • No trailing commas!
    • See Doctrine documentation.

Forms and config

TODO - sorry folks :P

Configuration management

  • Configuration is everything users and editors do not write
  • It's translatable
  • Examples:
    • views
    • view modes
    • image styles
    • permissions
    • content types
    • settings
  • Basically, anything that needs to be deployed.
  • Yay, it removed 50+ tables from the db!
  • Writes directly to files, not the DB
  • Written in YAML, not to hard to write/read and maps to arrays

Events

  • Like hooks, but Object Oriented
  • Less magic, more explicit
    • Should be easier to test!
  • Should also be simple bridge code, mostly.
  • Event: a thing that happens
  • Listener: code that responds to an event
  • Dispatcher: mediator of all event-responding
    • Think mediated-observer-pattern, not true observer-pattern
  • Subscriber: A class / service containing listeners
    • Implement EventSubscriberInterface
  • Warning:
    • Priorities are inverse from weights! (e.g.: 5 runs before 2)
    • There's not currently a way to ensure one runs after another
  • Rather than creating new hooks, create new events.

Random cool thing.

In PHP 5.3, $x ?: $y is equivalent to $x ? $x : $y!

Theming

  • Syntax:
    • {{ variable_name }} for printing a variable
    • Drill down using .: {{ array.element }} or {{ class.property }}
    • Comments: {# Comment #}
    • Limited PHP code, control structures, looping: {% hide(content.field_example) %}
    • Inheritance: {% block twig_block_name %}
  • Filters - functions for manipulating values:
    • {{ variable|escape('html') }}: safe strings
    • {{ variable|upper }}: all uppercase
  • Check out twiggy theme for examples.

Testing

  • Yay, you can use mock objects now!

  • Mocks pretend to be objects that your code is not testing!

  • PHPUnit supports them

  • Mock object pattern:

      $mock = $this->getMockBuilder('MyClass')
        ->disableOriginalConstructor()
        ->getMock();
      $mock->expects($this->CONDITION())
        ->method('myMethod')
        // either:
          ->will($this->DOSOMETHING());
        // or:
          ->with($this->ASSERTION());
    
  • Common will() methods:

    • will($this->returnValue('foo')) – Returns expected value from declared method.
    • will($this->returnArgument(1)) – Returns passed argument without change.
    • will($this->returnSelf()) – Returns the mocked object.
    • will(returnCallback('str_rot13')) – Returns a value after processing through a callback function.
  • Common with() methods:

    • with($this->equalTo('foo')) – Checks method argument is 'foo'.
    • with($this->equalTo('foo', 'bar')) – Checks method arguments are 'foo' and 'bar'.
    • with($this->greaterThan(5)) – Checks assertion against passed argument.
    • You can pass any PHPUnit assertion.
    • You can assert against each argument for the method.
  • Running tests: cd $drupalroot/core ; ./vendor/bin/phpunit

  • Unit tests should extend UnitTestCase.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment