This document provides tips and best practices for staying sane as a Drupal developer. It discusses that 80% of building Drupal sites is configuration, while the remaining 20% requires customization. It emphasizes using Drupal APIs and hooks, playing well with contributed modules, and following coding standards and best practices like version control, automated testing and deployment, and documentation.
Staying Sane with Drupal (A Develper's Survival Guide)Oscar Merida
Drupal is a powerful content management framework and among the most succesful PHP projects out there. Working with Drupal's modules and theme layer means that for any problem there's more than one way to that that. Picking a good solution, or dealing with the choices of previous developers will make you pull your hair out. I'll look at what you can do to make working with Drupal, shall we say, enjoyable? We'll look at how to evaluate contributed modules, what modules should be in all your installations, examine coding conventions in Drupal, and talk about development best practices for Drupal sites.
This presentation introduces the Drupal 8 configuration management system (CMI). Learn why configuration management is one of the most eagerly anticipated features of Drupal 8, and how it has the potential to completely change the workflow we use for building sites with Drupal. By addressing a number of long-standing issues in Drupal, CMI helps to separate content from configuration, provides a simple user interface for transporting configuration changes between multiple instances of the same site, and gives developers a consistent way to store and retrieve configuration in their code that is guaranteed to work with the rest of management tools provided.
Here's what we'll cover in this presentation:
- What is configuration management, and what problems does it solve
- The CMI user interface, and changes for site-builders
- The CMI API, and changes for modules developers
- What you can start learning now to ensure you're ready to use CMI
This workshop conducted by the team member of Inspire Chittagong (Mizanur Rahaman Mizan and Saad Amin). Workshop was in East Delta Univeristy. There was a session relating to the infos and also another one fully focusing on the practical theme development
Staying Sane with Drupal (A Develper's Survival Guide)Oscar Merida
Drupal is a powerful content management framework and among the most succesful PHP projects out there. Working with Drupal's modules and theme layer means that for any problem there's more than one way to that that. Picking a good solution, or dealing with the choices of previous developers will make you pull your hair out. I'll look at what you can do to make working with Drupal, shall we say, enjoyable? We'll look at how to evaluate contributed modules, what modules should be in all your installations, examine coding conventions in Drupal, and talk about development best practices for Drupal sites.
This presentation introduces the Drupal 8 configuration management system (CMI). Learn why configuration management is one of the most eagerly anticipated features of Drupal 8, and how it has the potential to completely change the workflow we use for building sites with Drupal. By addressing a number of long-standing issues in Drupal, CMI helps to separate content from configuration, provides a simple user interface for transporting configuration changes between multiple instances of the same site, and gives developers a consistent way to store and retrieve configuration in their code that is guaranteed to work with the rest of management tools provided.
Here's what we'll cover in this presentation:
- What is configuration management, and what problems does it solve
- The CMI user interface, and changes for site-builders
- The CMI API, and changes for modules developers
- What you can start learning now to ensure you're ready to use CMI
This workshop conducted by the team member of Inspire Chittagong (Mizanur Rahaman Mizan and Saad Amin). Workshop was in East Delta Univeristy. There was a session relating to the infos and also another one fully focusing on the practical theme development
Drupal 7 Theming - Behind the Scenes: PHP control flow starting from entering URL to browser displaying webpage. Covers Theme info file, regions, an Rendear Arrays (Phoenix User Group 1/25/2012)
The presentation covers:
*Adding JS to the page, both at module and theme level
*Writing Drupal aware JS code
*Libraries management
*Ajax framework
*Drupal JS functions
*Drupal JS theme functions
[2015/2016] Local data storage for web-based mobile appsIvano Malavolta
This presentation has been developed in the context of the Mobile Applications Development course, DISIM, University of L'Aquila (Italy), Spring 2016.
http://www.ivanomalavolta.com
Explains the basics of creating a new WordPress theme; outlining some useful functions, explains some usage in OOP PHP, briefly describes the WordPress themes API.
In this session you will learn:
Including Files at Request Time: jsp:include
Understanding jsp:include vs. <%@ include … %>
Options for Deploying Applets
Using jsp:plugin
Attributes of the jsp:plugin Element
Using JavaBeans Components in JSP Documents
Background: What Are Beans?
Using Beans: Basic Tasks
Setting Simple Bean Properties: jsp:setProperty
JSP Page That Uses StringBean(Code)
Conditional Bean Operations
Sharing Beans in Four Different Ways
Session-Based Sharing: Code
Application-Based Sharing: Code
Application-Based Sharing: Result
For more information, visit this link: https://www.mindsmapped.com/courses/software-development/online-java-training-for-beginners/
Becoming a drupal master builder - Given at Drupal Camp London 2016
I've been building Drupal sites for a number of years and have a broad experience building Drupal sites with various levels of complexity. I often work with other agencies to build Drupal sites or to migrate existing sites and as a result I will often see some very common mistakes and errors that shouldn't be happening. Due to Drupal's popularity I also see Drupal sites in the wild and can clearly see the same mistakes going on there as well.
During this talk I'll show some basic site building tips as well as some more complex and technical strategies that will make your Drupal sites better and more maintainable. Rather than just show you what to do, I'll also be explaining why doing those things are important and how developers and their websites will benefit from them. Although I'll be mainly concentrating on Drupal 7, some of these techniques are also applicable to Drupal 8.
Arcadian Learning is an Industrial Training Company with 50 years of Industry Expertise on Planning, Implementation and Operation of the Networks Offering six months Industrial Training program on Cloud Computing, Telecom, Big Data and Application Development.
The Android developer should have the knowledge of fundamentals of Android layouts, Widgets, UIs and Web Services & how to program your app’s interaction with activities and services.
http://www.arcadianlearning.com/application-web-development.html
Drupal 7 Theming - Behind the Scenes: PHP control flow starting from entering URL to browser displaying webpage. Covers Theme info file, regions, an Rendear Arrays (Phoenix User Group 1/25/2012)
The presentation covers:
*Adding JS to the page, both at module and theme level
*Writing Drupal aware JS code
*Libraries management
*Ajax framework
*Drupal JS functions
*Drupal JS theme functions
[2015/2016] Local data storage for web-based mobile appsIvano Malavolta
This presentation has been developed in the context of the Mobile Applications Development course, DISIM, University of L'Aquila (Italy), Spring 2016.
http://www.ivanomalavolta.com
Explains the basics of creating a new WordPress theme; outlining some useful functions, explains some usage in OOP PHP, briefly describes the WordPress themes API.
In this session you will learn:
Including Files at Request Time: jsp:include
Understanding jsp:include vs. <%@ include … %>
Options for Deploying Applets
Using jsp:plugin
Attributes of the jsp:plugin Element
Using JavaBeans Components in JSP Documents
Background: What Are Beans?
Using Beans: Basic Tasks
Setting Simple Bean Properties: jsp:setProperty
JSP Page That Uses StringBean(Code)
Conditional Bean Operations
Sharing Beans in Four Different Ways
Session-Based Sharing: Code
Application-Based Sharing: Code
Application-Based Sharing: Result
For more information, visit this link: https://www.mindsmapped.com/courses/software-development/online-java-training-for-beginners/
Becoming a drupal master builder - Given at Drupal Camp London 2016
I've been building Drupal sites for a number of years and have a broad experience building Drupal sites with various levels of complexity. I often work with other agencies to build Drupal sites or to migrate existing sites and as a result I will often see some very common mistakes and errors that shouldn't be happening. Due to Drupal's popularity I also see Drupal sites in the wild and can clearly see the same mistakes going on there as well.
During this talk I'll show some basic site building tips as well as some more complex and technical strategies that will make your Drupal sites better and more maintainable. Rather than just show you what to do, I'll also be explaining why doing those things are important and how developers and their websites will benefit from them. Although I'll be mainly concentrating on Drupal 7, some of these techniques are also applicable to Drupal 8.
Arcadian Learning is an Industrial Training Company with 50 years of Industry Expertise on Planning, Implementation and Operation of the Networks Offering six months Industrial Training program on Cloud Computing, Telecom, Big Data and Application Development.
The Android developer should have the knowledge of fundamentals of Android layouts, Widgets, UIs and Web Services & how to program your app’s interaction with activities and services.
http://www.arcadianlearning.com/application-web-development.html
Caracterísiticas del Periodismo Digital en Bolivia 2012Tonny Lopez
Un mapeo de medios digitales en Bolivia realizado por Cecilia Banegas, corresponsal del Observatorio Nacional de Medios (ONADEM) de la Fundación Unir Bolivia
This presentation was delivered on 11th May, 2014 in Drupal Camp Pakistan held in DatumSquare IT Services Islamabad. Contents of the presentation contains some basics stuff for designers, themers and coders.
This presentation will show the latest Web Components technologies and examples, and whether you should be using Web Components now. (spoiler alert: you should be!)
Slides from our CodeMash 2013 Precompiler session, "Web Development with Python and Django", including a breezy introduction to the Python programming language and the Django web framework. The example code repository is available at https://github.com/finiteloopsoftware/django-precompiler/
Frame - Feature Management for Productive Machine LearningDavid Stein
Presented at the ML Platforms Meetup at Pinterest HQ in San Francisco on August 16, 2018.
Abstract: At LinkedIn we observed that much of the complexity in our machine learning applications was in their feature preparation workflows. To address this problem, we built Frame, a shared virtual feature store that provides a unified abstraction layer for accessing features by name. Frame removes the need for feature consumers to deal directly with underlying data sources, which are often different across computing environments. By simplifying feature preparation, Frame has made ML applications at LinkedIn easier to build, modify, and understand.
Are you still on PHP 5.6-which will be EOL'd at the end of this year?! PHP 7 was released at the very end of 2015 and brought with it long awaited features to the PHP programming language while striving to keep backwards-compatibility. In this talk, I'll cover the new features including Static Type Hints, new operators, array de-referencing that you can use in your own Drupal modules to make your life easier. I'll also introduce a tool to assess how ready an existing PHP 5 codebase is to migrate to PHP 7.
Symfony console: build awesome command line scripts with easeOscar Merida
Utility scripts to kick off scheduled jobs and perform routing maintenance tasks are integral parts of any web application. You can also use them to easily integrate with your ticketing system, post to slack, or automate any number of tedious daily tasks. However, dealing with command line switches and options, getting user input, and providing meaningful output can be tedious and tricky to do yourself. In this talk, I'll introduce Symfony's console component which can handle a lot of boilerplate code for you so you can focus on the task at hand. After this talk, you'll know how to structure a basic command line app, get user input, and even package it up as a standalone phar file for others to use.
Building with Virtual Development EnvironmentsOscar Merida
Struggling with getting Apache, MySQL, PHP and everything else you need to start working on your next project? In this talk, we'll look at how to use Vagrant to setup a reusable development environment for Drupal. Vagrant automates setting it up so you can focus on getting work done, share identical environments with colleagues, and precisely match your local and production environments.
Building with Virtual Development EnvironmentsOscar Merida
Struggling with getting Apache, MySQL, PHP and everything else you need to start working on your next project? In this talk, we'll look at how to use Vagrant to setup a reusable development environment for Drupal. Vagrant automates setting it up so you can focus on getting work done, share identical environments with colleagues, and precisely match your local and production environments.
Publishing alchemy with markdown and pandocOscar Merida
Don't confine your content to a single output! Using markdown to write documents, coupled with the open-source pandoc tool, you can easily create a myriad of output format First, we'll learn about markdown syntax, and its different flavors. Then, we'll see how to use pandoc to generate HTML pages, eBooks, PDF documents, and even Word files.
In this talk, we'll look at the tools and modules available for migrating content into Drupal. I'll describe the workflow I've used to prepare, transform, and import thousands of records into Drupal. I'll share strategies for cleaning up and parsing data and doing it in a reliable, repeatable manner. You'll learn how to efficiently use PHP, Feeds, and Feeds XPath Parser modules to handle almost any data source thrown your way.
Do you have a mess of static HTML pages? Are you maintaining piecemeal legacy applications from the days before you had a shiny CMS? In this session we'll look at migration approaches for bringing that content into Drupal. We'll share what we've learned migrating a decade's worth of pages, content across a dozen database, and audio and video content - almost 15k nodes at last count - into Drupal 7.
This session will explore:
<ul>
<li>Deciding between manual and automated approaches to moving content
<li>Planning and scheduling large migrations to maintain your sanity
<li>What workflows and review steps are needed to ensure success
<li>Using the Migrate and other contributed modules to move content into Drupal.
</ul>
Multi-cluster Kubernetes Networking- Patterns, Projects and GuidelinesSanjeev Rampal
Talk presented at Kubernetes Community Day, New York, May 2024.
Technical summary of Multi-Cluster Kubernetes Networking architectures with focus on 4 key topics.
1) Key patterns for Multi-cluster architectures
2) Architectural comparison of several OSS/ CNCF projects to address these patterns
3) Evolution trends for the APIs of these projects
4) Some design recommendations & guidelines for adopting/ deploying these solutions.
# Internet Security: Safeguarding Your Digital World
In the contemporary digital age, the internet is a cornerstone of our daily lives. It connects us to vast amounts of information, provides platforms for communication, enables commerce, and offers endless entertainment. However, with these conveniences come significant security challenges. Internet security is essential to protect our digital identities, sensitive data, and overall online experience. This comprehensive guide explores the multifaceted world of internet security, providing insights into its importance, common threats, and effective strategies to safeguard your digital world.
## Understanding Internet Security
Internet security encompasses the measures and protocols used to protect information, devices, and networks from unauthorized access, attacks, and damage. It involves a wide range of practices designed to safeguard data confidentiality, integrity, and availability. Effective internet security is crucial for individuals, businesses, and governments alike, as cyber threats continue to evolve in complexity and scale.
### Key Components of Internet Security
1. **Confidentiality**: Ensuring that information is accessible only to those authorized to access it.
2. **Integrity**: Protecting information from being altered or tampered with by unauthorized parties.
3. **Availability**: Ensuring that authorized users have reliable access to information and resources when needed.
## Common Internet Security Threats
Cyber threats are numerous and constantly evolving. Understanding these threats is the first step in protecting against them. Some of the most common internet security threats include:
### Malware
Malware, or malicious software, is designed to harm, exploit, or otherwise compromise a device, network, or service. Common types of malware include:
- **Viruses**: Programs that attach themselves to legitimate software and replicate, spreading to other programs and files.
- **Worms**: Standalone malware that replicates itself to spread to other computers.
- **Trojan Horses**: Malicious software disguised as legitimate software.
- **Ransomware**: Malware that encrypts a user's files and demands a ransom for the decryption key.
- **Spyware**: Software that secretly monitors and collects user information.
### Phishing
Phishing is a social engineering attack that aims to steal sensitive information such as usernames, passwords, and credit card details. Attackers often masquerade as trusted entities in email or other communication channels, tricking victims into providing their information.
### Man-in-the-Middle (MitM) Attacks
MitM attacks occur when an attacker intercepts and potentially alters communication between two parties without their knowledge. This can lead to the unauthorized acquisition of sensitive information.
### Denial-of-Service (DoS) and Distributed Denial-of-Service (DDoS) Attacks
Bridging the Digital Gap Brad Spiegel Macon, GA Initiative.pptxBrad Spiegel Macon GA
Brad Spiegel Macon GA’s journey exemplifies the profound impact that one individual can have on their community. Through his unwavering dedication to digital inclusion, he’s not only bridging the gap in Macon but also setting an example for others to follow.
APNIC Foundation, presented by Ellisha Heppner at the PNG DNS Forum 2024APNIC
Ellisha Heppner, Grant Management Lead, presented an update on APNIC Foundation to the PNG DNS Forum held from 6 to 10 May, 2024 in Port Moresby, Papua New Guinea.
This 7-second Brain Wave Ritual Attracts Money To You.!nirahealhty
Discover the power of a simple 7-second brain wave ritual that can attract wealth and abundance into your life. By tapping into specific brain frequencies, this technique helps you manifest financial success effortlessly. Ready to transform your financial future? Try this powerful ritual and start attracting money today!
1.Wireless Communication System_Wireless communication is a broad term that i...JeyaPerumal1
Wireless communication involves the transmission of information over a distance without the help of wires, cables or any other forms of electrical conductors.
Wireless communication is a broad term that incorporates all procedures and forms of connecting and communicating between two or more devices using a wireless signal through wireless communication technologies and devices.
Features of Wireless Communication
The evolution of wireless technology has brought many advancements with its effective features.
The transmitted distance can be anywhere between a few meters (for example, a television's remote control) and thousands of kilometers (for example, radio communication).
Wireless communication can be used for cellular telephony, wireless access to the internet, wireless home networking, and so on.
1.Wireless Communication System_Wireless communication is a broad term that i...
Staying Sane with Drupal NEPHP
1. Staying Sane with Drupal
A Developer's Survival Guide
Oscar Merida, @omerida
Northeast PHP, Boston
August 2015
2. 80% of building sites with
Drupal is configuration (easy)
Credit: https://www.flickr.com/photos/jeepersmedia/12953571545/
3. The hard part is the final
20% of customization
• Functionality that is
new to Drupal
• or different than
assumptions
• Integration with
external systems
Credit: https://www.flickr.com/photos/jurvetson/15393495039
4. Drupal is procedural
• Not Object Oriented
• Many structures like nodes, forms, users, etc use StdClass
objects or arrays
• Not MVC like other PHP frameworks
• but there is separation of concerns between menu callbacks
& theme layers
• Hooks afford a way to alter existing functionality or implement
new features.
• Leverage hooks
5. Play Well with Others
• Don’t short circuit how
things work.
• If you're stuck, ask for help.
• "Always code as if the
person who ends up
maintaining your code is a
violent psychopath who
knows where you live."
• http://c2.com/cgi/wiki?
CodeForTheMaintainer
6. Use Drupal APIs
• EntityFieldQuery
• Form ArrayPI
• node_load(), node_presave(), node_* hooks
• Node Access System
7. Dig into the Documentation
• api.drupal.org has function definitions and
examples.
• Security -
https://www.drupal.org/writing-secure-code
• Check Project Issue Queues
9. Rules of the Road
• Use Version Control (git, svn, etc.)
• Use branches to manage workflow
• Replicate production environment in a VM
• Rule 0.1 - never edit files on live
10. Follow Drupal's coding standard.
• Everyone on the team must follow it.
• https://www.drupal.org/coding-standards
• Don't waste cycles arguing about which
standard to follow.
• Can use your IDE to follow a standard.
• BONUS: Use PHP CodeSniffer to enforce it.
11. Use Features
• Drupal saves a lot of configuration to the database,
• makes code sharing & deployments difficult.
• Use Features + Strongarm modules to export settings to
Features modules.
• Create one Feature module for each Content Type or Function
• Include related fields, Views, Display Suite settings, Panels &
Pages, Contexts, Path aliases, Rules,etc.
• Have a Base module with shared fields and global settings
like input formats.
12. Share Features
• Track your modules in VCS
• When you update codebase, check Features UI for
Overrides and resolve them.
13. Automate Deployments
• As simple as having a simple script to sync files
to your environments
• Or automagically update dev, stage, production
by pushing to the correct VCS branch
• https://www.freelock.com/node/1108
• BUT remember to keep sensitive information out
of VCS (like database credentials).
14. Don't Fear the Command Line
• Drush is faster and easier to automate than
going through the UI.
• Clearing caches - drush cc all
• DB Snapshot - drush sql-dump > ../mydb.sql
• Creating a user - drush user-create
• Reindexing search - drush search-index
16. Focus on building new solutions.
• Avoid “Not-invented-here” syndrome
• There's a module for that. In fact, there's
probably several …
http://dilbert.com/strip/2014-08-11
17. But with great power…
• Inherit technical debt
of a module.
• Keep up-to-date with
new releases,
especially security
releases.
• Sometimes you don't
need a module to
change things.
18. Evaluating a module
• Does the maintainer have other modules?
• Does it have a stable release?
• Does it have recent commits?
• Is the issue queue active?
• Does it have good documentation?
19. Practically core…
• Views (is in D8)
• Views Bulk Operations
• Features & Strongarm
• Pathauto & Token
• Webform
• Rules
• Email
• Link
• Smart Trim
• Redirect
• Entity Reference
• Entity API
• Entity Cache
20. Nice to Have
• Bean (better Blocks)
• Administration Views
• Display Suite
• Backup & Migrate
• Content Locking
• Menu Block
• Revisioning
• Add Another
22. Views
• GUI based Query Builder
• Has its own terminology
• Excels at building
display output.
• Not limited to HTML.
https://commons.wikimedia.org/wiki/File:Tower_Optical_Binoculars.jpg
23. Fields & Filters
• Fields - the fields to return from the query
• SELECT id, name, birthdate
• Filters - conditions to select items
• WHERE name=“smith”
24. Contextual Filters
• Apply filters based on external arguments.
• Filter values usually come from the URL path.
• Node ID
• User ID
• Term ID
25. Relationships
• Add a related table to the base query
• JOIN groups ON (groups.id=users.group_id)
• Can then pull in fields from other entites into
Fields, Filters, and Contexts.
26. Use an Existing View Programatically.
• views_embed_view(): Useful for building custom blocks
with logic while keeping them configurable in the Views UI.
function mymodule_view() {
$tid = (int) arg(2);
$preferred = views_embed_view('dept_resources', 'block_1', $tid);
// test if the view is empty by looking for view-empty class
if (false !== strpos($preferred, 'class="view-empty"')) {
$all = views_embed_view('dept_resources', 'block_2', $tid);
$block['content'] = $all;
} else {
$block['content'] = $preferred;
}
return $block;
}
27. Views Hooks
• Views API provides a number of hooks for
changing a view.
• hook_views_pre_view()
• hook_views_pre_ender()
• hook_views_query_alter()
• and more!
https://api.drupal.org/api/views/views.api.php/group/views_hooks/7
28. hook_views_pre_view()
• Runs at start of processing. Useful for changing
or cleaning up arguments.
function foo_views_pre_view(&$view, &$display_id, &$args) {
if ('map_legend' == $view->name) {
// get location short name from aliased view pat
// ex. "campus/fairfax-va"
$shortname = parse_path_shortname();
// get the campus node with the matching shortname
$node = foo_campus_lookup_shortname($shortname);
$args[0] = $node->nid;
}
}
29. hook_views_pre_render()
• Runs at start of rendering.
• Useful for changing titles, adding headers & footers,
replacing placeholders.
function foo_views_pre_render(&$view) {
if ('campus_map' == $view->name) {
if (isset($view->result[0]->nid)) {
$node = $view->result[0]->_field_data['nid']['entity'];
$view->set_title('Campuses for ' . $node->title);
}
return;
}
30. hook_views_query_alter()
• Alter a query before it runs.
• Helps deal with input edge cases.
function foo_views_query_alter(&$view, &$query) {
if ('campus_contacts' == $view->name) {
if ('mid-state' == arg(2)) {
$query->where[0]['conditions'][0]['value'] = 'Mid-State';
}
}
}
31. but sometimes…
• You need to query for a collection of Entities
• In that case, use EntityFieldQuery
• https://www.drupal.org/node/1343708
• Unless you're reading & writing your own custom
tables, don't use db_query().
32. function foo_lookup_shortname($short)
{
// now look up the node for this short to make sure it exists
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
->entityCondition('bundle', 'campus')
->propertyCondition('status', 1)
->fieldCondition('field_short_name', 'value', $short, '=')
->range(0, 1);
$result = $query->execute();
if (!$result || empty($result)) {
return false;
}
$ids = array_keys($result['node']);
$nodes = node_load_multiple($ids);
$node = array_pop($nodes); // return first
return $node;
}
34. Custom modules for:
• Implementing hooks
• Integration with 3rd party systems
• Custom entities
35. Use Permissions
• hook_perm defines permissions
• Check for custom permission in routes, views, etc.
• Avoid checking for one or more roles.
/**
* Implements hook_permission().
*/
function foo_email_digest_permission() {
return array(
'administer foo digest' => array(
'title' => t('Administer FOO Digest'),
'description' => t('Manage Digest settings.'),
),
);
}
36. Use Node Grants
• hook_node_grants defines
what "realms" a user works
with.
• A user can belong to one or
more groups in a realm.
• https://www.phase2technology.com/
drupal-7-node-access-grants-locks-
and-keys/
function foo_node_grants($account, $op) {
$grants = array();
// If a user is an admin then grant access to all
if (user_has_role('Site Admin', $account)) {
$admin_nids = foo_get_workspace_nids();
$grants['workspace_member'] = $admin_nids;
} else {
$ws_nids = foo_get_users_ws_nids($account);
// add the workspace nodes that the user
// is an owner of too.
$owner_nids = foo_get_owner_ws_nids($account);
$grants['workspace_member']
= array_merge($ws_nids, $owner_nids);
}
return $grants;
}
37. Use Node Grants, pt 2
• hook_node_access_records
control access to nodes.
• Control user access for
viewing, updating, deleting at
the node-level.
• Integrates with views and
search results.
function foo_node_access_records($n)
{
// don't clutter grants
if ('resource' !== $n->type) {
return;
}
$ws_nid = $n->field_workspace['und'][0]['target_id'];
if (empty($ws_nid)) {
return;
}
$grants = array();
$grants[] = array (
'realm' => 'workspace_member',
'gid' => $ws_nid,
'grant_view' => 1,
'grant_update' => 0,
'grant_delete' => 0,
'priority' => 0,
);
return $grants;
}
40. Expose tasks via Drush
• Make functionality
available via drush
• http://www.drush.org/en/
master/commands/
• Can then execute
them in Terminal
• easier to schedule
via cron too
/**
* Implements hook_drush_command().
*/
function foo_email_digest_drush_command() {
$items['foo-digest-send'] = array(
'description' => 'Send email digest.',
'aliases' => array('foodig'),
);
return $items;
}
function drush_foo_email_digest_foo_digest_send() {
foo_digest_send();
}
41. Best Practices
• Create an admin settings form
• Keep editable settings outside of code
• Consider having switches to toggle functionality
on/off
• Provide theme functions
• Themes and other modules can override
rendered display
43. Basics
• t() - Output a translatable string with replacements
• check_plain() - Output sanitized text. Important if
you’re taking user input and displaying it.
• filter_xss() - Output sanitized text, allow some HTML
tags. Important if you’re taking user input and
displaying it.
• See also filter_admin_xss()
• arg() - Get an argument from the URL path.
Remember to filter input!
44. get_current_user()
• Retrieve the user object for the current user.
• Better than global $user;
<?php
function foo() {
$user = get_current_user();
if (0 == $user->uid) {
drupal_goto('user/login');
}
}
45. current_path()
• Returns the current unaliased path. Useful if a
hook should only run on one or more specific
paths.
if ('node/15' == current_path()) {
// customize this node
}
if ('publications' == current_path()) {
// customize this node
}
46. drupal_get_path_alias()
• Returns the aliased path for an internal path.
// check alias of current page
$alias = drupal_get_path_alias();
if ('about' == $alias) {
// customize the 'About Us' page
}
47. menu_get_item()
• Returns the currents menu item path. Similar to
current_path(), easier to test if something
should only run on a set of pages.
$menu = menu_get_item();
// make sure we're on any user profile page
if ('user/%' !== $menu['path']) {
return
}
48. drupal_goto()
• Redirect client to another URL. Allows other
modules to rewrite paths.
if (0 == $user->uid) {
drupal_goto('user/login');
}
50. drupal_set_message()
• Display success, warning, or error messages to
client (web or Drush).
<?php
function foo() {
$node = node_load('node/' . $nid);
// ...do some stuff to $node
// something went wrong
drupal_set_message(
'Could not use node',
'warning', // status|warning|error
);
}
51. Thank You. Questions?
• Follow me @omerida
• Slides:
• http://phpa.me/drupal-sane-nephp
• Feedback:
• https://joind.in/talk/view/14727
• Editor-in-chief of php[architect]
• Check out http://world.phparch.com