Jeff Geerling's Blog: Increase the Guzzle HTTP Client request timeout in Drupal 8

Planet Drupal - Thu, 18/08/2016 - 18:56

During some migration operations on a Drupal 8 site, I needed to make an HTTP request that took > 30 seconds to return all the data... and when I ran the migration, I'd end up with exceptions like:

Migration failed with source plugin exception: Error message: cURL error 28: Operation timed out after 29992 milliseconds with 2031262 out of 2262702 bytes received (see http://curl.haxx.se/libcurl/c/libcurl-errors.html).

The solution, it turns out, is pretty simple! Drupal's \Drupal\Core\Http\ClientFactory is the default way that plugins like Migrate's HTTP fetching plugin get a Guzzle client to make HTTP requests (though you could swap things out if you want via services.yml), and in the code for that factory, there's a line after the defaults (where the 'timeout' => 30 is defined) like:

Categories: Elsewhere

Simon Désaulniers: [GSOC] Week 10&11&12 Report

Planet Debian - Thu, 18/08/2016 - 17:09
Week 10 & 11

During these two weeks, I’ve worked hard on paginating values on the DHT.

Value pagination

As explained on my post on data persistence, we’ve had network traffic issues. The solution we have found for this is to use the queries (see also this) to filter data on the remote peer we’re communicating with. The queries let us select fields of a value instead of fetching whole values. This way, we can fetch values with unique ids. The pagination is the process of first selecting all value ids for a given hash, then making a separate “get” request packet for each of the values.

This feature makes the DHT more friendly with UDP. In fact, UDP packets can be dropped when of size greater than the UDP MTU. Paginating values will help this as all UDP packets will now contain only one value.

Week 12

I’ve been working on making the “put” request lighter, again using queries. This is a key feature which will make it possible to enable data persistence. In fact, it enables us to send values to a peer only if it doesn’t already have the value we’re announcing. This will substantially reduce the overall traffic. This feature is still being tested. The last thing I have to do is to demonstrate the reduction of network traffic.

Categories: Elsewhere

Valuebound: Get your Drupal8 Development platform ready with Drush8!

Planet Drupal - Thu, 18/08/2016 - 15:17

As we all know, we need Drush8 for our Drupal8 development platform. I have tried installing Drush 8 using composer, but sometimes it turns out to be a disaster, especially when you try to install Drush 8 on the Digital Ocean Droplet having Ubuntu 16.04.

I have faced the same issue in the last few months to get the Drupal8 development platform ready with Drush8. So I have decided to find a solution to fix that forever. Well, finally found one which are the following lines of commands.

cd ~ php -r "readfile('http://files.drush.org/drush.phar');" > drush chmod +x drush sudo mv drush /usr/bin drush init

If you are…

Categories: Elsewhere

Drupal core announcements: We can add big new things to Drupal 8, but how do we decide what to add?

Planet Drupal - Thu, 18/08/2016 - 14:48

Drupal 8 introduced the use of Semantic Versioning, which practically means the use of three levels of version numbers. The current release is Drupal 8.1.8. While increments of the last number are done for bugfixes, the middle number is incremented when we add new features in a backwards compatible way. That allows us to add big new things to Drupal 8 while it is still compatible with all your themes and modules. We successfully added some new modules like BigPipe, Place Block, etc.

But how do we decide what will get in core? Should people come up with ideas, build them, and once they are done, they are either added in core or not? No. Looking for feedback at the end is a huge waste of time, because maybe the idea is not a good fit for core, or it clashes with another improvement in the works. But how would one go about getting feedback earlier?

We held two well attended core conversations at the last DrupalCon in New Orleans titled The potential in Drupal 8.x and how to realize it and Approaches for UX changes big and small both of which discussed a more agile approach to avoid wasting time.

The proposal is to separate the ideation and prototyping process from implementation. Within the implementation section the potential use of experimental modules helps with making the perfecting process more granular for modules. We are already actively using that approach for implementation. On the other hand the ideation process is still to be better defined. That is where we need your feedback now.

See https://www.drupal.org/node/2785735 for the issue to discuss this. Looking forward to your feedback there.

Categories: Elsewhere

Mediacurrent: How Drupal won an SEO game without really trying

Planet Drupal - Thu, 18/08/2016 - 14:23

At Mediacurrent we architected and built a Drupal site for a department of a prominent U.S. university several years ago. As part of maintaining and supporting the site over the years, we have observed how well it has performed in search engine rankings, often out-performing other sites across campus built on other platforms.

Categories: Elsewhere

KnackForge: Drupal Commerce - PayPal payment was successful but order not completed

Planet Drupal - Thu, 18/08/2016 - 12:00
Drupal Commerce - PayPal payment was successful but order not completed

Most of us use PayPal as a payment gateway for our eCommerce sites. Zero upfront, No maintenance fee, API availability and documentation makes anyone easy to get started. At times online references offer out-dated documentation or doesn't apply to us due to account type (Business / Individual), Country of the account holder, etc. We had this tough time when we wanted to set up Auto return to Drupal website.

Thu, 08/18/2016 - 15:30 Tag(s) Drupal planet Drupal 7 DropThemes.in drupal-commerce
Categories: Elsewhere

Zlatan Todorić: DebConf16 - new age in Debian community gathering

Planet Debian - Thu, 18/08/2016 - 11:19


Finally got some time to write this blog post. DebConf for me is always something special, a family gathering of weird combination of geeks (or is weird a default geek state?). To be honest, I finally can compare Debian as hacker conference to other so-called hacker conferences. With that hat on, I can say that Debian is by far the most organized and highest quality conference. Maybe I am biased, but I don't care too much about that. I simply love Debian and that is no secret. So lets dive into my view on DebConf16 which was held in Cape Town, South Africa.

Cape Town

This was the first time we had conference on African continent (and I now see for the first time DebConf bid for Asia, which leaves only Australia and beautiful Pacific islands to start a bid). Cape Town by itself, is pretty much Europe-like city. That was kinda a bum for me on first day, especially as we were hosted at University of Cape Town (which is quite beautiful uni) and the surrounding neighborhood was very European. Almost right after the first day I was fine because I started exploring the huge city. Cape Town is really huge, it has by stats ~4mil people, and unofficially it has ~6mil. Certainly a lot to explore and I hope one day to be back there (I actually hope as soon as possible).

The good, bad and ugly

I will start with bad and ugly as I want to finish with good notes.

Racism down there is still HUGE. You don't have signs on the road saying that, but there is clearly separation between white and black people. The houses near uni all had fences on walls (most of them even electrical ones with sharp blades on it) with bars on windows. That just bring tensions and certainly doesn't improve anything. To be honest, if someone wants to break in they still can do easily so the fences maybe need to bring intimidation but they actually only bring tension (my personal view). Also many houses have sign of Armed Force Response (something in those lines) where in case someone would start breaking in, armed forces would come to protect the home.

Also compared to workforce, white appear to hold most of profit/big business positions and fields, while black are street workers, bar workers etc etc. On the street you can feel from time to time the tension between people. Going out to bars also showed the separation - they were either almost exclusively white or exclusively black. Very sad state to see. Sharing love and mixing is something that pushes us forward and here I saw clear blockades for such things.

The bad part of Cape Town is, and this is not only special to Cape Town but to almost all major cities, is that small crime is on wide scale. Pickpocketing here is something you must pay attention to it. To me, personally, nothing happened but I heard a lot of stories from my friends on whom were such activities attempted (although I am not sure did the criminals succeed).

Enough of bad as my blog post will not change this and it is a topic for debate and active involvement which I can't unfortunately do at this moment.


There are so many great local people I met! As I mentioned, I want to visit that city again and again and again. If you don't fear of those bad things, this city has great local cuisine, a lot of great people, awesome art soul and they dance with heart (I guess when you live in rough times, you try to use free time at your best). There were difference between white and black bars/clubs - white were almost like standard European, a lot of drinking and not much dancing, and black were a lot of dancing and not much drinking (maybe the economical power has something to do with it but I certainly felt more love in black bars).

Cape Town has awesome mountain, the Table Mountain. I went on hiking with my friends, and I must say (again to myself) - do the damn hiking as much as possible. After every hike I feel so inspired, that I will start thinking that I hate myself for not doing it more often! The view from Table mountain is just majestic (you can even see the Cape of Good Hope). The WOW moments are just firing up in you.

Now lets transfer to DebConf itself. As always, organization was on quite high level. I loved the badge design, it had a map and nice amount of information on it. The place we stayed was kinda not that good but if you take it into account that those a old student dorms (in we all were in female student dorm :D ) it is pretty fancy by its own account. Talks were near which is always good. The general layout of talks and front desk position was perfect in my opinion. All in one place basically.

Wine and Cheese this year was kinda funny story because of the cheese restrictions but Cheese cabal managed to pull out things. It was actually very well organized. Met some new people during the party/ceremony which always makes me grow as a person. Cultural mix on DebConf is just fantastic. Not only you learn a lot about Debian, hacking on it, but sheer cultural diversity makes this small con such a vibrant place and home to a lot.

Debian Dinner happened in Aquarium were I had nice dinner and chat with my old friends. Aquarium by itself is a thing where you can visit and see a lot of strange creatures that live on this third rock from Sun.

Speaking of old friends - I love that I Apollo again rejoined us (by missing the DebConf15), seeing Joel again (and he finally visited Banja Luka as aftermath!), mbiebl, ah, moray, Milan, santiago and tons of others. Of course we always miss a few such as zack and vorlon this year (but they had pretty okay-ish reasons I would say).

Speaking of new friends, I made few local friends which makes me happy and at least one Indian/Hindu friend. Why did I mention this separately - well we had an accident during Group Photo (btw, where is our Lithuanian, German based nowdays, photographer?!) where 3 laptops of our GSoC students were stolen :( . I was luckily enough to, on behalf of Purism, donate Librem11 prototype to one of them, which ended up being the Indian friend. She is working on real time communications which is of interest also to Purism for our future projects.

Regarding Debian Day Trip, Joel and me opted out and we went on our own adventure through Cape Town in pursue of meeting and talking to local people, finding out interesting things which proved to be a great decision. We found about their first Thursday of month festival and we found about Mama Africa restaurant. That restaurant is going into special memories (me playing drums with local band must always be a special memory, right?!).

Huh, to be honest writing about DebConf would probably need a book by itself and I always try to keep my posts as short as possible so I will try to stop here (maybe I write few bits in future more about it but hardly).

Now the notes. Although I saw the racial segregation, I also saw the hope. These things need time. I come from country that is torn apart in nationalism and religious hate so I understand this issues is hard and deep on so many levels. While the tensions are high, I see people try to talk about it, try to find solution and I feel it is slowly transforming into open society, where we will realize that there is only one race on this planet and it is called - HUMAN RACE. We are all earthlings, and as sooner we realize that, sooner we will be on path to really build society up and not fake things that actually are enslaving our minds.

I just want in the end to say thank you DebConf, thank you Debian and everyone could learn from this community as a model (which can be improved!) for future societies.

Categories: Elsewhere

Unimity Solutions Drupal Blog: Video Annotations: A Powerful and Innovative Tool for Education

Planet Drupal - Thu, 18/08/2016 - 08:51

According to John J Medina a famous molecular biologist “Vision trumps all other senses.” Human mind is attracted to remember dynamic pictures rather than listen to words or read long texts. Advancement in multimedia has enabled teachers to impart visual representation of content in the class room.

Categories: Elsewhere

Drupalize.Me: Learn by Mentoring at DrupalCon

Planet Drupal - Thu, 18/08/2016 - 08:37

DrupalCon is a great opportunity to learn all kinds of new skills and grow professionally. For the 3 days of the main conference in Dublin (September 27–29) there will be sessions on just about everything related to Drupal that you could want. One amazing opportunity that you may not be aware of though is the Mentored Sprint on Friday, September 30th. This is a great place for new folks to learn the ropes of our community and how to contribute back. What may be less talked about is the chance to be a mentor.

Categories: Elsewhere

Norbert Tretkowski: No MariaDB MaxScale in Debian

Planet Debian - Thu, 18/08/2016 - 08:00

Last weekend I started working on a MariaDB MaxScale package for Debian, of course with the intention to upload it into the official Debian repository.

Today I got pointed to an article by Michael "Monty" Widenius he published two days ago. It explains the recent license change of MaxScale from GPL so BSL with the release of MaxScale 2.0 beta. Justin Swanhart summarized the situation, and I could not agree more.

Looks like we will not see MaxScale 2.0 in Debian any time soon...

Categories: Elsewhere

Roy Scholten: Vetting Drupal product ideas

Planet Drupal - Wed, 17/08/2016 - 23:57

We’ve made big strides since Drupalcon New Orleans in how we add new features to Drupal core. The concept of experimental modules has already helped us introduce features like a new way to add blocks to a page, content moderation and workflow tools and a whole new approach for editing all the things on a page while staying at that page.

In New Orleans we started to define the process for making these kinds of big changes. Probably the most important and defining aspect of it is that we’re (finally!) enabling a clearer separation between vetting ideas first, implementation second.

True to form we specified and detailed the latter part first :-)

So, on to that first part, vetting Drupal product ideas. In my core conversation I outlined the need for making bigger UX changes, faster and suggested possible approaches for how to design and develop those, borrowing heavily from the Lean UX method

Since then, we’ve been reminded that we really do need a clearly defined space to discuss the strategic value of proposed new features. A place to decide if a given idea is desirable and viable as an addition to core.

The point being: core product manager with help from Drupal UX team members wrote up a proposal for how to propose core product ideas and what’s needed to turn a good idea into an actionable plan.

It needs your feedback. Please read and share your thoughts.

Tags: drupaluxprocessdrupalplanetSub title: Agree on why and what before figuring out the how
Categories: Elsewhere

Gunnar Wolf: Talking about the Debian keyring in Investigaciones Nucleares, UNAM

Planet Debian - Wed, 17/08/2016 - 20:47

For the readers of my blog that happen to be in Mexico City, I was invited to give a talk at Instituto de Ciencias Nucleares, Ciudad Universitaria, UNAM.

I will be at Auditorio Marcos Moshinsky, on August 26 starting at 13:00. Auditorio Marcos Moshinsky is where we met for the early (~1996-1997) Mexico Linux User Group meetings. And... Wow. I'm amazed to realize it's been twenty years that I arrived there, young and innocent, the newest of what looked like a sect obsessed with world domination and a penguin fetish.

AttachmentSize llavero_chico.png220.84 KB llavero_orig.png1.64 MB
Categories: Elsewhere

Mediacurrent: DrupalCon NOLA: The People Behind the Usernames

Planet Drupal - Wed, 17/08/2016 - 20:33

As we work every day on our own projects, with our own deadlines and priorities, it is often too easy to forget about the entire community of others using Drupal in much the same way. When we're working with Drupal in our various capacities, there is no shortage of methods to interact with the community and contribute back, but those aren't the focus of this post.

Categories: Elsewhere

myDropWizard.com: Drupal 6 security updates for Panels!

Planet Drupal - Wed, 17/08/2016 - 20:16

As you may know, Drupal 6 has reached End-of-Life (EOL) which means the Drupal Security Team is no longer doing Security Advisories or working on security patches for Drupal 6 core or contrib modules - but the Drupal 6 LTS vendors are and we're one of them!

Today, there is a Critical security releases for the Panels modules for multiple Access Bypass vulnerabilities.

The first vulnerability allows anonymous users to use AJAX callbacks to pull content and configuration from Panels, which allow them to access private data. And the second, allows authenticated users with permission to use the Panels IPE to modify the Panels display for pages that they don't have permission to otherwise edit.

See the security advisory for Drupal 7 for more information.

Here you can download the patch for 6.x-3.x!

If you have a Drupal 6 site using the Panels module, we recommend you update immediately! We have already deployed the patch for all of our Drupal 6 Long-Term Support clients. :-)

If you'd like all your Drupal 6 modules to receive security updates and have the fixes deployed the same day they're released, please check out our D6LTS plans.

Note: if you use the myDropWizard module (totally free!), you'll be alerted to these and any future security updates, and will be able to use drush to install them (even though they won't necessarily have a release on Drupal.org).

Categories: Elsewhere

Rakesh's DSoC 16 blog: Last week - GSoC16 - Detected and Solved Merge Conflicts in Drupal8.

Planet Drupal - Wed, 17/08/2016 - 20:04
Last week - GSoC16 - Detected and Solved Merge Conflicts in Drupal8. rakesh Wed, 08/17/2016 - 23:34
Categories: Elsewhere

Miloš Bovan: The final week of Google Summer of Code 2016

Planet Drupal - Wed, 17/08/2016 - 19:56
The final week of Google Summer of Code 2016

It’s been more than 13 warm weeks since I’ve started to work on my Google Summer of Code 2016 - Mailhandler project. During the past few weeks, I finished the coding and worked on latest improvements related to documentation.

In the past week, the project documentation has been updated which was the last step before merging Github repository and Sandbox project into Mailhandler. Drupal 8 release section was updated and it summarizes the features of D8 version. If you are wondering where you can use the code I developed this summer, feel free to read about real Mailhanlder use-cases.

This week, I am doing the latest cleanups and preparing the project for the final evaluation. It is the second evaluation after I submitted the midterm evaluation. In case you missed the previous posts from Google Summer of Code series, I am providing the project retrospect below.

Project Retrospect

In early February, in an ordinary conversation, a friend of mine told me about this year’s Google Summer of Code program. I got interested in it since I took apart in GHOP (The Google Highly Open Participation Contest; This program was replaced with Google Code-In) during high-school.

In March, I’ve found out that Drupal will be one of the participating organizations and since I did a Drupal internship last year, this seemed to be a perfect opportunity to continue open-source contribution.

Among many interesting project ideas, I decided for “Port Mailhandler to Drupal 8”. Miro Dietiker proposed the project and during the proposal discussions, Primoz Hmeljak joined the mentoring team too.

The great news came in April. I was one of the 11 students chosen to contribute Drupal this summer! First Yay moment!

The project progress could have been followed on this blog, so I’m will not go deeper into it.

3 months of work passed quickly and at this point, I can confirm that I learned a ton of new things. I improved not only my coding skills but communication and project management skills too.

In my opinion, we reached all the goals we put on the paper in April. All the features defined in the proposal were developed, tested and documented.

Google Summer of Code is a great program and I would sincerely recommend all the students to consider participating in it.

Future plans

The future plans about the module are related to its maintenance. Inmail is still under development and it seems it will be ready for an alpha release very soon. In the following days, I am going to create an issue about nice-to-have features of Mailhandler. This issue could serve as a place for Drupal community to discuss the possible ways of the future Mailhandler development.

Thank you note

Last but not least, I would like to give huge thanks to my mentors (Miro Dietiker and Primoz Hmeljak) for being so supportive, helpful and flexible during this summer. Their mentoring helped me in many ways - from the proposal re-definition in April/May, endless code iterations, discussions of different ideas to blog post reviews, including this one :).

I would like to thank my company too for allowing me to contribute Drupal via this program and Google for giving me an opportunity to participate in this great program.



Milos Wed, 08/17/2016 - 19:56 Tags Drupal Google Summer of Code Open source Drupal Planet Add new comment
Categories: Elsewhere

Raphaël Hertzog: Freexian’s report about Debian Long Term Support, July 2016

Planet Debian - Wed, 17/08/2016 - 16:45

Like each month, here comes a report about the work of paid contributors to Debian LTS.

Individual reports

In July, 136.6 work hours have been dispatched among 11 paid contributors. Their reports are available:

  • Antoine Beaupré has been allocated 4 hours again but in the end he put back his 8 pending hours in the pool for the next months.
  • Balint Reczey did 18 hours (out of 7 hours allocated + 2 remaining, thus keeping 2 extra hours for August).
  • Ben Hutchings did 15 hours (out of 14.7 hours allocated + 1 remaining, keeping 0.7 extra hour for August).
  • Brian May did 14.7 hours.
  • Chris Lamb did 14 hours (out of 14.7 hours, thus keeping 0.7 hours for next month).
  • Emilio Pozuelo Monfort did 13 hours (out of 14.7 hours allocated, thus keeping 1.7 hours extra hours for August).
  • Guido Günther did 8 hours.
  • Markus Koschany did 14.7 hours.
  • Ola Lundqvist did 14 hours (out of 14.7 hours assigned, thus keeping 0.7 extra hours for August).
  • Santiago Ruano Rincón did 14 hours (out of 14.7h allocated + 11.25 remaining, the 11.95 extra hours will be put back in the global pool as Santiago is stepping down).
  • Thorsten Alteholz did 14.7 hours.
Evolution of the situation

The number of sponsored hours jumped to 159 hours per month thanks to GitHub joining as our second platinum sponsor (funding 3 days of work per month)! Our funding goal is getting closer but it’s not there yet.

The security tracker currently lists 22 packages with a known CVE and the dla-needed.txt file likewise. That’s a sharp decline compared to last month.

Thanks to our sponsors

New sponsors are in bold.

No comment | Liked this article? Click here. | My blog is Flattr-enabled.

Categories: Elsewhere

Jamie McClelland: Nice Work Apertium

Planet Debian - Wed, 17/08/2016 - 16:07

For the last few years I have been periodically testing out apertium and today I did again and was pleasantly surprised with the quality of the english-spanish and spanish-english translations (and also their nifty web site translator).

So, I dusted off some of my geeky code to make it easier to use and continue testing.

For starters...

sudo apt-get install apertium-en-es xclip coreutils

Then, I added the following to my .muttrc file:

macro pager <F2> "<enter-command>set pipe_decode<enter><pipe-entry> sed '1,/^$/d' | apertium es-en | less<enter><enter-command>unset pipe_decode<enter>" "translate from spanish"

If you press F2 while reading a message in spanish it will print out the English translation.

If you use vim, you can create ~/.vim/plugins/apertium.vim with:

function s:Translate() silent !clear execute "! apertium en-es " . bufname("%") . " | tee >(xclip)" endfunction command Translate :call <SID>Translate()

Then, you can type the command:


And it will display the English to Spanish translation of the file you are editing and copy the translation into your clip board so you can paste it into your document.

Categories: Elsewhere

lakshminp.com: Tagged services in Drupal 8

Planet Drupal - Wed, 17/08/2016 - 16:07

We saw how to write a simple service container in Drupal earlier. We shall build a tagged service now. To illustrate a proper use case for tagged services, let's contrive a scenario where you add a pipeline custom filters to user text before rendering it on the page.

First, clone the code which will be used in this post.

$ git clone git@github.com:drupal8book/process_text.git

Checkout the first version of the code where we take custom text from user, process and display it in a page without using services.

$ cd process_text $ git checkout -f just-filtering

We get custom text from a user using a config form.

class CustomTextSettingForm extends ConfigFormBase { /** * {@inheritdoc} */ protected function getEditableConfigNames() { return [ 'process_text.settings', ]; } /** * {@inheritdoc} */ public function getFormId() { return 'custom_text_setting_form'; } /** * {@inheritdoc} */ public function buildForm(array $form, FormStateInterface $form_state) { $config = $this->config('process_text.settings'); $form['custom_text'] = [ '#type' => 'textarea', '#title' => $this->t('Custom Text'), '#default_value' => $config->get('custom_text'), ]; return parent::buildForm($form, $form_state); } /** * {@inheritdoc} */ public function validateForm(array &$form, FormStateInterface $form_state) { parent::validateForm($form, $form_state); } /** * {@inheritdoc} */ public function submitForm(array &$form, FormStateInterface $form_state) { parent::submitForm($form, $form_state); $this->config('process_text.settings') ->set('custom_text', $form_state->getValue('custom_text')) ->save(); $form_state->setRedirect('process_text.show'); } }

We save it as a piece of configuration called process_text.settings.custom_text.

Before rendering this text, let's say you would want to:

  • Remove any <div> tags.
  • Substitute a token [greeting] with <span class"greeting">hello world</span> throughout the text.

We get the text and do all the above processing inside a custom controller.

class ProcessTextController extends ControllerBase { /** * Processtext. * * @return string * Return processed custom text. */ public function processText() { $custom_text = \Drupal::config('process_text.settings')->get('custom_text'); // do processing // remove divs $custom_text = str_replace(["<div>", "</div>"], "", $custom_text); // replace greeting tokens $custom_text = str_replace("[greeting]", '<span class="greeting">hello world</span>', $custom_text); return [ '#type' => 'markup', '#markup' => $custom_text ]; } }

This is good, but we could do better. What if we change the filter applying mechanism? We have to change this code. Instead, let's convert it into a service.

$ cd process_text $ git checkout -f services-first-cut

Our text filter service takes a set of filters and applies them to a given text when we call applyFilters.

class TextFilterService { private $filters = []; /** * @param Filter $filter */ public function addFilter(Filter $filter) { $this->filters[] = $filter; } /** * applies all filters to given text and returns * filtered text. * * @param string $txt * * @return string */ public function applyFilters($txt) { foreach ($this->filters as $filter) { $txt = $filter->apply_filter($txt); } return $txt; } }

We need to crate a services.yml file for the above service.

services: process_text.text_filter: class: Drupal\process_text\TextFilterService

Here's how the processText function text looks now.

public function processText() { $custom_text = \Drupal::config('process_text.settings')->get('custom_text'); // do processing using a service $filter_service = \Drupal::service('process_text.text_filter'); // remove divs $filter_service->addFilter(new RemoveDivs()); // substitute greeting token $filter_service->addFilter(new Greeting()); // apply all the above filters $custom_text = $filter_service->applyFilters($custom_text); return [ '#type' => 'markup', '#markup' => $custom_text ]; }

Now the filter applying mechanism is swappable. We can add write a different functionality and inject that implementation using service containers.

Now, what if we want to add a new filter to this code, like, enclosing the whole text within a <p> tag.

Sure. We could do that.

Let's checkout the specific tag where we add a new filter.

$ cd process_text $ git checkout -f add-new-filter

We build that filter.

class EnclosePTags implements Filter { public function apply_filter($txt) { return '<p>'. $txt . '</p>'; } }

…and add it to the set of filters being applied.

public function processText() { $custom_text = \Drupal::config('process_text.settings')->get('custom_text'); // do processing using a service $filter_service = \Drupal::service('process_text.text_filter'); // remove divs $filter_service->addFilter(new RemoveDivs()); // substitute greeting token $filter_service->addFilter(new Greeting()); // Enclose p tags $filter_service->addFilter(new EnclosePTags()); // apply all the above filters $custom_text = $filter_service->applyFilters($custom_text); return [ '#type' => 'markup', '#markup' => $custom_text ]; }

How about injecting the filter adding mechanism itself? Wouldn't it be cool if we are able to add new filters without changing this part of the code? Not to mention the fact that the code will be more testable than before if we follow this approach. This is exactly what tagged services help us accomplish.

Let's write each filter as a tagged service.

$ cd process_text $ git checkout -f tagged-services

Here's how our process_text.services.yml looks now.

services: process_text.text_filter: class: Drupal\process_text\TextFilterService tags: - { name: service_collector, tag: text_filter, call: addFilter } remove_divs_filter: class: Drupal\process_text\TextFilter\RemoveDivs tags: - { name: text_filter } greeting_filter: class: Drupal\process_text\TextFilter\Greeting tags: - { name: text_filter } enclose_p_filter: class: Drupal\process_text\TextFilter\EnclosePTags tags: - { name: text_filter }

There are many changes here. Firstly, all the filters have been converted to services themselves. The have a common tag called text_filter. The main service also has a few changes. It has a tag called service_collector and a tag parameter call. This ritual of creating a service container and adding a set of tagged services is such a common pattern that Drupal 8 has a special tag to do this, called the service_collector. This tag takes an additional parameter called call which indicates what function has to be called in the service to add all the tagged services.

What happens is, Drupal's TaggedHandlersPass picks up all services with "service_collector" tag, finds services which have the same tag as that of this service(text_filter in our case) and calls the method in call to consume the tagged service definition. If you're coming from Symfony world, this might seem familiar for you. In order to execute some custom code, like applying a set of filters, we implement CompilerPassInterface, which is run whenever the service cotainer(ApplyFilter in our case) is being built. You can find more about CompilerPassInterface here.

Your controller code looks a lot simpler now.

public function processText() { $custom_text = \Drupal::config('process_text.settings')->get('custom_text'); // do processing using a service $filter_service = \Drupal::service('process_text.text_filter'); $custom_text = $filter_service->applyFilters($custom_text); return [ '#type' => 'markup', '#markup' => $custom_text ]; }

Now, all you need to add new filters is to update the service yaml file with the new filter service and tag it with "text_filter" tag.

Tagged services in the wild

Drupal allows developers to add a new authentication mechanism using tagged services. The authentication_collector is defined in core.services.yml.

authentication_collector: class: Drupal\Core\Authentication\AuthenticationCollector tags: - { name: service_collector, tag: authentication_provider, call: addProvider }

To add a new authentication provider, one has to implement the AuthenticationProviderInterface and flesh out the applies and authenticate functions. This will be the subject of another post.

Here's how the addProvider function looks like:

public function addProvider(AuthenticationProviderInterface $provider, $provider_id, $priority = 0, $global = FALSE) { $this->providers[$provider_id] = $provider; $this->providerOrders[$priority][$provider_id] = $provider; // Force the providers to be re-sorted. $this->sortedProviders = NULL; if ($global) { $this->globalProviders[$provider_id] = TRUE; } }

And here's how we would register our hypothetical authentication provider service.

services: authentication.custom_auth: class: Drupal\custom_auth\Authentication\Provider\CustomAuth tags: - { name: authentication_provider }

Another example is the breadcrumb manager service.

breadcrumb: class: Drupal\Core\Breadcrumb\BreadcrumbManager arguments: ['@module_handler'] tags: - { name: service_collector, tag: breadcrumb_builder, call: addBuilder }

To add breadcrumbs from your module, you would need to implement BreadcrumbBuilderInterface and add the following entry to your services.yml,

services: foo.breadcrumb: class: Drupal\foo\MyBreadcrumbBuilder tags: - { name: breadcrumb_builder, priority: 100 }

The BreadcrumbManager::addBuilder collects all breadcrumb bilders and builds it using the BreadcrumbManager::build function.

public function addBuilder(BreadcrumbBuilderInterface $builder, $priority) { $this->builders[$priority][] = $builder; // Force the builders to be re-sorted. $this->sortedBuilders = NULL; } Drupal, Drupal 8, Drupal Planet
Categories: Elsewhere


Subscribe to jfhovinne aggregator - Elsewhere