How does Drupal 7 Work? Tess Flynn, KDØPQK www.deninet.com
About the Author Bachelor of Computer Science Used Drupal since 4.7 Switched from self-built PHP CMS Current Job: Not in Drupal! But she d like it to be! Anime, B-Movies, Cloud, Linux, MST3k, Drupal, OSS, Scifi, Ham Radio, Heavy Metal, & occasional OSNews podcaster. In other words: Just another wench looking for a bolt to turn... IT Education, middleware International experience 2 Contact me
Why do this? Lesson 1 3
Common reasons Contribute to core Help create better sites. Curiosity? Because. 4
Personal Reasons Simple curiosity Learn from other s code Drupal has many years of development behind it Equates to many years of programming experience! To own Drupal To contribute back 5
Owning Drupal Core ignorant Core knowledgeable 6
Methodology Lesson 2 7
What we need IDE and Debugger Provides development environment Allows us to halt and step through execution *AMP Stack Runtime environment for web applications Captive local server required Linux, Mac, Windows LAMP, MAMP, WAMP Drupal Obviously! 8
What we want Open Source Drupal is Open Source Free Expense Nonprofessional intent Actively Maintained Use tools that are used! 9
Integrated Dev Environment +PDT Eclipse Project IBM-backed open source, multi-platform IDE http://www.eclipse.org PHP Develop Toolkit (PDT) Provides PHP tools for Eclipse http://www.eclipse.org/pdt 10
Debugger Open Source PHP Debugger Functions as a PHP extension Multi-platform (kinda) Compiled library available for Windows Source code for Linux, Mac http://xdebug.org 11
*AMP Stack 12 Research before you install! Pre-packaged stacks Simplify installation, but May use config shortcuts or gimmicks Individual Packages (The hard way) https://httpd.apache.org http://www.mysql.com http://php.net Linux Use your distro s package manager Avoid graphical tools, use command line
Any 7.x version will work A copy of Drupal http://drupal.org/download Click here! 13
How do I set this up? There s a session for that! Arming for war against bugs When Friday May 18 th, 14:30 Room 3 111 (Electric Citizen room) Track Coding and Development Experience Level Intermediate 14
Documentation and Resources Drupal API documentation http://api.drupal.org Includes full code for core functions Pro Drupal 7 Development Available from http://www.apress.com Printed and DRM-free PDF PHP language documentation http://php.net/docs.php 15
Drupal Architecture Lesson 3 16
*AMP Stack Drupal Architecture Drupal Entities, Modules, Blocks, Menus, Users, Permissions, and Themes PHP Data Objects (PDO) PHP Web Server Apache, IIS, nginx Database Server MySQL, PostgreSQL, SQLite Operating System File System 17 Source: Pro Drupal 7 Development, Tomlinson et al
Drupal Layers Renders HTML for display to user Determine who has access to what Menus route page requests! Makes Drupal extendable by implementing hooks. 18 Provides base structures around Drupal is based Source: http://drupal.org/getting-started/before/overview
Booting Drupal Lesson 4 19
index.php define('drupal_root', getcwd()); require_once DRUPAL_ROOT. '/includes/bootstrap.inc'; drupal_bootstrap(drupal_bootstrap_full); menu_execute_active_handler(); It s just four lines of code! 1. Set the DRUPAL_ROOT variable 2. Import bootstrap.inc 3. Boot up drupal 4. Route the page request 20
drupal_bootstrap() Located in bootstrap.inc Where code needed for all requests is kept Is invoked multiple times Sometimes recursively! Loads Drupal subsystems in eight phases Current phase taken as a parameter DRUPAL_BOOTSTRAP_* constants 21
Boot Phases 1 DRUPAL_BOOTSTRAP_CONFIGURATION 2 DRUPAL_BOOTSTRAP_PAGE_CACHE 3 DRUPAL_BOOTSTRAP_DATABASE 4 DRUPAL_BOOTSTRAP_VARIABLES 5 DRUPAL_BOOTSTRAP_SESSION 6 DRUPAL_BOOTSTRAP_PAGE_HEADER 7 DRUPAL_BOOTSTRAP_LANGUAGE 8 DRUPAL_BOOTSTRAP_FULL 22
Phase 0: Full Bootstrap DRUPAL_BOOTSTRAP_FULL Not a real phase Shortcut to run all phases in order Later phases dependant on earlier ones Invoking _FULL invokes all other phases 23
Phase 1: Configuration _drupal_bootstrap_configuration() Located in includes/boostrap.inc Set error and exception handler Route PHP errors through Drupal s render chain Initialize the PHP environment Generate q, the requested page path Set PHP session parameters Start the page timer drupal_settings_initialize() Located in bootstrap.inc Load settings.php Set the base URL, cookie and session values 24
Phase 2: Page Cache _drupal_bootstrap_page_cache() Located in includes/bootstrap.inc Load includes/cache.inc Load page from cache if enabled Re-invoke drupal_bootstrap() Pass DRUPAL_BOOTSTRAP_VARIABLES DRUPAL_BOOTSTRAP_DATABASE called as a result If page found in cache Serve it to the user Halt bootup 25
Phase 3: Database _drupal_bootstrap_database() Located in includes/bootstrap.inc Check if installation is being run Switch to install.php Initialize database abstraction layer Load includes/database/database.inc Register OOP autoloaders Aids in PDO user 26
Phase 4: Variables _drupal_bootstrap_variables() Located in includes/bootstrap.inc Initialize locking system Load includes/lock.inc Used to prevent control access to shared resources Load variables from database Used by core and modules for configuration storage variable_get(), variable_set() Load Enabled modules necessary for bootstrap 27
What are these bootstrap modules? devel Contrib module, but common for development sites Dblog System logging to database Implements hook_watchdog() Overlay Core module Administration interface May be disabled 28
Phase 5: Session drupal_session_initialize() Located in includes/session.inc Load includes/session.inc If the user already has a session Initialize the session If the user is anon or not logged in Initialize an anonymous user object Assign it to a unique session 29
Phase 6: Page Header _drupal_bootstrap_page_header() Located in includes/bootstrap.inc Invoke hook_boot() In modules necessary for bootstrap Send default HTTP headers If Drupal isn t operating from the command line 30
Phase 7: Language drupal_language_initialize() Located in includes/bootstrap.inc Initialize the language system for translations Only if Drupal has multiple languages enabled, skip otherwise Load includes/language.inc 31
Phase 8: Finalize Bootstrap _drupal_bootstrap_full() Located in includes/common.inc Load several required core *.inc files from the includes folder Remaining files loaded by modules Load all enabled modules Initialize q to a valid Drupal path Initialize the theme Invoke hook_init() 32
Typical Default Modules [skipped] modules loaded during boostrap Devel_generate, devel are contrib modules 33 block comment dashboard devel_generate* field_sql_storage file help list node options path search system text update devel[skipped] color contextual dblog[skipped] field field_ui filter image menu number overlay[skipped] rdf shortcut taxonomy toolbar user standard
Module Loading Getting contributed code into memory 34
Magical modules? Core *.inc files Drupal What happens here??? Module Directory My.module 35 Drupal itself is invoked by the Web Server Modules are just text files until Drupal loads them! Modules need to be dynamically (ondemand) loaded Load only what we need *.module files
Loading Module Code include_once($module_file_path); 36 That s it! PHP s own loading mechanism Need not be executed at the top of a *.php file May be executed in other statements, like functions, ifs and loops! include_once() used to avoid WSOD Instead of require(), require_once() Uses _once to avoid duplicate import
It can t be that simple! It isn t, but include_once() is the core mechanism Modules loaded at two points DRUPAL_BOOTSTRAP_VARIABLES for boostrap modules DRUPAL_BOOTSTRAP_FULL for all other modules 37
Loading Bootstrap Modules drupal_bootstrap() _drupal_bootstrap_variables() Loops through list provided by module_list() Scans for *.module files, returns paths module_load_all($bootstrap = TRUE) module_list($bootstrap = TRUE) Loop through list of modules drupal_load($type= module, $name) 38 Calls include_once()
Loading regular Modules Basically the same as bootstrap drupal_bootstrap() _drupal_bootstrap_full() module_load_all($bootstrap = FALSE) module_list($bootstrap = FALSE) Loop through list of modules drupal_load($type= module, $name) 39
Invoking hooks Calling module code 40
Hooks Module Drupal Drupal passes execution to the module at key points ( hooks ) Allows modules to interact, enhance or extend Drupal core Modules implement hooks by creating a function with a certain name mymodulename_hookname() 41
Calling Hooks Drupal core knows: Which modules are enabled The name of all module functions When it wants to call a hook We need a quick way to Call all functions that implement the hook Pass arbitrary parameters 42
module_invoke() module_invoke($module_name, $hook_name) Calls a function $hook_name in module $module_name Additional params passed at the end of module_invoke() module_invoke( my, hook, $param) Relies on PHP s func_get_args() 43 Uses PHP s call_user_func_array() Takes function name as a string Passes all parameters as an array http://php.net/manual/en/function.call-user-funcarray.php
What module_invoke() does Returns results of hook invocation module_invoke($modulename, $hookname) Get additional arguments using func_get_args() If the module implements the hook return call_user_func_array($modulename. '_'. $hook, $arguments) 44
module_invoke_all() Commonly used to invoke hooks Same parameters as module_invoke() except No $modulename Loops through all modules that implement that hook Returns array containing results of all called hooks 45
Menu Routing Getting from URL to Page 46
The Job of the Menu System http://example.com/index.php?q=the/requested/page Drupal Path What we think it does Provide menus? Takes a Drupal path, and returns a page What it really does Match the Drupal path to PHP code to execute Which returns the page Subject to access control 47
How Modules Define Menu Items function motleymod_menu(){ $items[my/motley/page] = array( 'page callback' => 'motleymod_my_page', ); return $items; } function motleymod_my_page(){ return "<p>this is my motley page.</p>"; } 48 Implementation of hook_menu() Relatively unchanged from Drupal 5 Key of $items is menu path page callback has function name Not a hook, just a plain-old-function Returns page content to display
A More Complex Example function motleymod_menu{ $items[my/motley/page] = array( 'page callback' => 'motleymod_my_page', ); $items[admin/config/motley] = array( 'title' => "Configure Motley Module!", 'page callback' => 'drupal_get_form', 'page arguments' => array('motleymod_admin_settings'), 'access arguments' => array('administer motleymod'), 'type' => MENU_NORMAL_ITEM, 'file' => 'motleymod.admin.inc' ); } return $items; 49 One hook, multiple menu items! Page callback calls Drupal Function? Renders a form based on an array Array specified by page arguments
What the heck is all that stuff!? Parameter Title Page Callback Page Arguments Access Arguments Type File Meaning The title of the page to display. It's used both in the <title> tag of the generated page, as well as in the <h1> tag in the body section of the page. The the magic parameter. It tells Drupal what function to call! Specifies the arguments to pass to the function specified in the Page Callback parameter. Specifies the access permissions (under admin/people/permissions) the current user must have in order to access the page. The kind of menu item this item represents. More on that later. Tells Drupal in what file to find the function specified in the Page Callback parameter. 50
menu_execute_active_handler() 51 Located in includes/menu.inc Checks if site is offline If yes, return site offline page Call menu_get_item($path) Returns the page callback name that matches the path On failure, return 404 Check user access, if specified Return Access Denied on failure Call call_user_func_array() passing the page callback name Call drupal_deliver_page() Sends HTML back to the browser!
The Path to a Better Drupal Web Services Context Core Initiative 52
What s wrong with Drupal? Drupal 7 is heavy All code loaded for all requests Even when not necessary, unused! Designed for Desktop browser workflow Refresh entire page on each request Works poorly for REST, mobile apps This is why we need Drupal 8! 53
What will change in Drupal 8? Replace of many core functions with the Symfony Project http://symfony-project.org Routing will definitely change Module hooks, TBD A lot, or nothing at all. -- Larry Garfield, WSCCI lead 54 Source: Flickr, picture by Heyrocker
More about D8 and Symphony Musical CMS: How Symfony is coming to Drupal When Saturday May 19 th, 13:15 Room 3 210 (Gorton Studios room) Track Coding and Development Experience Level Intermediate 55
56 Dedicated to Kimiko 20?? May, 2012