Morpht: Simple Social Service links for Drupal 8

Planet Drupal - 27. September 2018 - 13:46

There are couple of online tools, and integration modules to get sharing widget to your site. They rely on JavaScript and the security of your users is questionable. This article will show you how to create a simple yet flexible and safer service sharing widget without line of JavaScript.

Background

The main reason why not to use some of the tools like AddToAny is the security. This is often a case for government or other public facing project such as GovCMS. Sharing widget of these services is not connecting directly to the social service, but it is processed on their servers first. And they can track the user on through the web because of the fingerprint they made. Another reason is that the JS code is often served from a CDN so you don’t know when the code changes and how? Have they put them some malicious script? I don’t want this on my site. And clients often as well. :)

Thankfully each service provide a simple way how to share content and we will use that.

Final example

You can see the final result in action with different styling applied at our example GovCMS 8 demo page (scroll down to the bottom of page).

Site build

First we need to prepare the data structure. For our purpose we will need to create a custom block type, but it can be easily done as a paragraph too.

Custom block name: Social Share
Machine name: [social_share]

And throw in few Boolean fields. One for each service.

Field label: [Human readable name] e.g. “Twitter”
Machine name: [machine_name] e.g. “social_share_twitter” – this one is important and we will use it later.

Go to the manage display screen of the block (/admin/structure/block/block-content/manage/social_share/display) and change the Output format to Custom. Then fill in the Custom output for TRUE with the text you like to see on the link e.g. "Share to twitter".

Now we are able to create a new block of the Social share type and check some of these checkboxes. Users will see only the Labels as result.

Theming

The fun part is changing the output of the field from simple label to actual share link.
First we need to know how the final link looks like.
Links examples:

Facebook: http://www.facebook.com/share.php?u=[PAGE_URL]&title=[PAGE_TITLE] Twitter: http://twitter.com/intent/tweet?status=[PAGE_TITLE]+[PAGE_URL] LinkedIn: http://www.linkedin.com/shareArticle?mini=true&url=[PAGE_URL]&title=[PAGE_TITLE]&source=[BASE_PATH] E-mail: mailto:?subject=Interesting page [PAGE_TITLE]&body=Check out this site I came across [PAGE_URL]

To get it work we need a current page Page URL, Page title, and Base path. Only the page URL is directly accessible from TWIG template. The other two needs to be prepared in preprocess. Lets add these in the theme_name.theme file.

/** * Implements template_preprocess_field(). */ function theme_name_preprocess_field(&$variables, $hook) { switch ($variables['field_name']) { case 'field_social_share_twitter': $request = \Drupal::request(); $route_match = \Drupal::routeMatch(); $title = \Drupal::service('title_resolver') ->getTitle($request, $route_match->getRouteObject()); if (is_array($title)) { $variables['node_title'] = $title['#markup']; } else { $variables['node_title'] = (string) $title; } $variables['base_path'] = base_path(); break; } }

As we probably will have more then one service we should use the DRY approach here. So we create extra function for the variable generation.

/** * Preprocess field_social_share. */ function _theme_name_preprocess_field__social_shares(&$variables) { $request = \Drupal::request(); $route_match = \Drupal::routeMatch(); $title = \Drupal::service('title_resolver') ->getTitle($request, $route_match->getRouteObject()); if (is_array($title)) { $variables['node_title'] = $title['#markup']; } else { $variables['node_title'] = (string) $title; } $variables['base_path'] = base_path(); }

And we than call it for various cases. If some service will need more variables it will be easy to add it in different function. So we don’t process whats not required.

/** * Implements template_preprocess_field(). */ function theme_name_preprocess_field(&$variables, $hook) { switch ($variables['field_name']) { case 'field_social_share_facebook': _theme_name_preprocess_field__social_shares($variables); break; case 'field_social_share_twitter': _theme_name_preprocess_field__social_shares($variables); break; case 'field_social_share_linkedin': _theme_name_preprocess_field__social_shares($variables); break; case 'field_social_share_email': _theme_name_preprocess_field__social_shares($variables); break; } }

Now we have the Node title and Base path prepared to be used in field templates.

Enable twig debug and look in the markup for the checkbox. You will see couple of suggestions, the one we are looking for is field--field-social-share-twitter.html.twig.

As the output should be single link item it is safe to assume we can remove all the labels condition and the single/multiple check as well. On the other hand we need to ensure that if the checkbox is unchecked it will not output any value. That is particularly hard in TWIG as it doesn’t have any universal information about the state of checkbox. It has only access to the actual value. But since we don’t know the value of custom label we cannot use it. However there is a small workaround we can use. Remember we hav not set the FALSE value.
We can check if the field is outputting any #markup. The empty FALSE value will not produce anything, hence the condition will fail.

{% if item.content['#markup'] %}

Here is the full code for field template:

{% set classes = [ 'social-share__service', 'social-share__service--twitter', ] %} {% for item in items %} {% if item.content['#markup'] %} "http://twitter.com/intent/tweet?status={{ node_title }}+{{ url('') }}" title="Share to {{ item.content }}">{{ item.content }} {% endif %} {% endfor %}


For other services you need to adapt it. But it will still follow the same pattern.

And we are done. Now your block should return links to sharing current page to the service.

Pro tip:

So far we have not use any contrib module. But obviously your client would like to have some fancy staying applied. You can add everything in the theme, but that will be only one hardcoded option. For easier live of editors you can use Entity Class formatter module to easily add classes to the block from a select list. You can provide multiple select list for Size, Color, Rounded corners, Style etc.

Result

At this point we have the simple social share widget ready. We can select which predefined services will show in each instance and how will they look. E.g. On blog post you can have sharing for Twitter, Facebook and Email styled as small rounded icons. But with another instance of the block you can have only large squared LinkedIn icon + label shown on Job offering content type.

Further notes

After I wrote first draft of this article new module appeared which work in very similar way. Give it a try at Better Social Sharing Buttons. It will be quicker to get up ad running as it has predefined styles and services, but that can be a drawback at the same time. If I need different style, or extra service it can be harder to add it.

OpenSense Labs: Power Of Microservices Architecture In Drupal Development

Planet Drupal - 27. September 2018 - 13:45
Power Of Microservices Architecture In Drupal Development Shankar Thu, 09/27/2018 - 17:15

One of the reasons why The New York Times is able to catch up to its growing user base is its inclination towards technological advancements. That was evident when it leveraged the power of microservice architecture via a remodelled video publishing platform to scale with their newsroom demands. They also moved their infrastructure to the cloud which resulted in a stable and scalable email platform, powered by a suite of microservices, for sending emails to the readers.


Why are big enterprises like The New York Times leaning towards microservices? Microservices has grown exponentially and holds an astronomical future for the digital businesses. It will be interesting to see how traditional CMS like Drupal finds a place in the world of microservices. But before plunging into all that, one might wonder where did this ‘microservices’ thing originate from?

Tracing the roots in the UNIX world

New Relic has compiled an interesting and brief timeline of the evolution of microservices. Microservices has its roots in the Unix world that takes us back to more than three decades ago.

As a term, microservices was first documented in 2011 by Martin Fowler

Service-oriented architecture (SOA), a design principle where services are offered to other components by application components via communication protocol over a network, was all the rage decades ago. Due to a superabundance of failures and costly implementations, the SOA earned a poor reputation and took a backseat. Martin Fowler, among others, has said that microservices are a new spin on SOA.

As a term, it was first documented in 2011 by Fowler at a software architects’ workshop.

In 2012, a presentation was given by James Lewis at the 33rd Degree in Krakow which was titled “Microservices - Java, the Unix Way”. This delineated microservices as a means of building software more rapidly by dividing and conquering and used Conway’s Law to structure teams.

Since that time, the adoption of microservice architecture has grown and many organisations are going for microservices as their default style for building enterprise applications.

Understanding the terminology Source: LeanIX GmbH

What are microservices? Microservices are an architecture for splitting a monolithic application into smaller pieces. Each of those pieces offers a certain function through a well-defined and carefully handled API.

The collection delivers the same overall business value like the monolithic application with the difference being these independently working individual pieces in microservices. That means they can be updated swiftly without impacting an entire application.

“The microservice architectural style is an approach to developing a single application as a suite of small services, each running in its own process and communicating with lightweight mechanisms, often an HTTP resource API. These services are built around business capabilities and independently deployable by fully automated deployment machinery. There is a bare minimum of centralized management of these services, which may be written in different programming languages and use different data storage technologies”. - Martin Fowler

"A microservice architectural style is an approach to develop a single application as a suite of small services, each running in its own process and communicating with lightweight mechanisms, often an HTTP resource API".

Netflix is an unsurpassed example of microservices adoption. It moved from a traditional development model with several engineers producing a monolithic DVD-rental application to a microservices architecture. Small teams could focus on the end-to-end development of hundreds of microservices that work together to serve digital entertainment to millions of Netflix customers every day.

Source: LeanIX GmbH

The main difference between monolithic and microservices architecture, as can be seen in the depiction above, is that all the features and functionalities were under a single umbrella. That is, they were under a single instance sharing a single database. With microservices, each feature is allotted a different microservice, managing its own data, and performing a different set of functionalities.

How good or bad are microservices? Source: Logentries

The benefits of microservices are laid out below:

  • Autonomous deployments: You can update a service without having to redeploy the entire application and rollback or roll forward an update during mishaps. Fixing bugs and feature releases are much more manageable with fewer challenges.
  • Autonomous development: Building, testing and deploying a service would need a single development team leading to perpetual innovation and swift release cadence.
  • Small teams: Teams can lay their focus onto one service thereby simplifying the understanding of the codebase with the smaller scope for each service.
  • Isolation of faults: Downtime in one of the services won’t affect the overall application. This does not mean that you get resiliency for free.
  • Tech stack mixture: Technology that is deemed most fit for a service can be selected by the teams.
  • Scalability at granular levels: Independent scaling of services is possible.

Some of the challenges are outlined below:

  • Intricacy: More moving parts are there in microservice application than the equivalent monolithic application.
  • Development and testing: Developing against service dependencies would need a different approach and testing service dependencies is difficult particularly when the application is evolving rapidly.
  • The dearth of administration: The decentralised approach for building microservices may lead to numerous languages and frameworks thereby making it harder to manage.
  • Network congestion and latency: Usage of granular services can result in more inter-service communication. Chances are that if the chain of service dependencies gets too elongated, additional latency can be a challenge.
  • Data integrity: Data consistency can be a hurdle with each microservice responsible for its own data persistence.
  • Management: Correlated logging across services can become a formidable task.
  • Update issues: If not for a careful design, several services updating at a given time could result in backward or forward compatibility.
  • Team skill-set: As the highly distributed systems, microservices require a team with the right mix of skills and experience.
Taking Drupal into the context

Drupal is a monolith. How can it survive this trend of microservices? Drupal, being an amazing content management framework, provides a great content editing experience and has been pioneering digital innovation. With that being said, microservices architecture can be used for development and deployment of applications using Drupal. Let’s see how Drupal can put into the scheme of things.

Demonstration at DrupalCon Vienna 2017

A presentation held at DrupalCon Vienna 2017 demonstrated an effective way of integrating Drupal 8 in a microservices architecture.
 
Drupal 8 proved to be a useful content management framework for this implementing microservices architecture because of its:

  • Symfony components,
  • Composer to manage external dependencies,
  • and the magnificent results of the Web Services and Context Core Initiative (WSCCI).
     


It exhibited the delegation of asynchronous work from Drupal to a set of very reactive applications written in Go with some assistance of RabbitMq queues. Elasticsearch was leveraged as a common data storage between services and REST endpoints were exposed where the endpoints could notify back to Drupal.
 
Furthermore, methods of connecting websocket server to push and pull messages between services were shown. To run all these services in a controlled and replicable manner, services of Ansible and Docker were extracted.

Demonstration at Drupal Developer Days Lisbon 2018

Another session at Drupal Developer Days Lisbon 2018 delineated how the citizen portal of the city of Reykjavik (Iceland) was relaunched using Drupal and microservices.
 
With the incorporation of more than 100 web services ranging from simple services like registering a dog or renewing a driver’s license to the intricate services like the admissions of children to school or updating the residential address.


Powered by Drupal 8, this new portal integrates the services with a microservices architecture using JSON Schema as communication protocol. The microservices architecture was chosen to let centralised data collection and presentation in a single portal while simultaneously incorporating a heterogeneous landscape of services autonomously from one another.

Predictions ahead

Oracle’s Cloud Predictions 2018 report states that by 2020, the lion’s share of new applications will be powered by microservices architectures.

Open source has given a whopping push to the microservices architecture. Its several components support continuous integration and delivery pipelines, microservices platforms, containers, container management and orchestration, container registry service, and serverless capability.

Open source has given a whopping push to the microservices architecture

Adoption of cross-cloud containers like Docker and Kubernetes is on the upwards trajectory and developers consider an open cloud stack to prevent vendor lock-in.

Source: Market Research Future

According to a report on Market Research Future, the microservices architecture market is expected to reach $32.01 billion by 2023 with a Compound Annual Growth Rate (CAGR) of around 16.17% during the forecast period.

Another report on Research and Markets for the forecast period of 2017 to 2023 states that as far as the ‘Market Analysis’ is concerned, the rise in the cloud adoption is integral for microservices market. This is because the microservices architectures function on smaller and simpler services. Also, there is a high demand from North American companies as they have implemented it in e-commerce, financial, and travel services. This has helped in storing data and information cost-effectively and enhanced the efficacy, agility and scalability.

The report on Research and Markets has an interesting ‘Countries and Vertical Analysis’ vis-à-vis microservices. Most of the major players are in the American region with the prominent vendors covered in the report include the likes of Cognizant, IBM Corporation, Datawire, Salesforce, Infosys Ltd., MuleSoft Inc., and Software AG. Japan, the US and China are expected to witness a tremendous growth in microservices adoption.

Conclusion

Microservices architectures streamline the overall application development lifecycle leading to quicker testing, higher quality and more releases. Such an architecture can be hugely useful for efficient management of Drupal-based projects. Innovation has always been something Drupal is greatly supportive of. Adopting a microservice architecture for Drupal development is possible and is extremely fruitful.

Organisations should be wary of their digital business ecosystem and should understand the challenges that they might have to encounter during its adoption. Opensense Labs has been in the constant pursuit of bringing a positive change for our valued partners with our expertise in Drupal.

Contact us at hello@opensenselabs.com to know more about microservices architectures and its value to your organisational setup.

blog banner blog image microservices Drupal microservices Drupal 8 Drupal CMS Drupal and microservices UNIX Service-oriented architecture SOA Microservices architecture DrupalCon Drupal Developer Days monolithic monolithic architecture Blog Type Articles Is it a good read ? On

Aldi-Notebook für 300 Euro: Medion Akoya E2294 im Kurztest

heise online Newsticker - 27. September 2018 - 13:30
Aldi Nord verkauft ab dem 27. September ein 11,6-Zoll-Notebook mit IPS-Touchscreen, 360-Grad-Scharnieren und drei Jahren Garantie für 300 Euro.

Salesforce: Applikationen stärker integrieren

heise online Newsticker - 27. September 2018 - 13:30
Der CRM-Anbieter gelobt auf der Dreamforce-Konferenz Besserung bei der Integration der Akquisitionen vergangener Jahre..

Sigma will eigene Vollformatkamera mit L-Mount entwickeln

heise online Newsticker - 27. September 2018 - 13:30
Sigma will zur L-Mount-Alliance nicht nur Objektive beisteuern. Auch an einer neuen, eigenen Kamera mit L-Mount arbeitet der Hersteller.

Photokina: Event-Tipps rund um die Photokina 2018

heise online Newsticker - 27. September 2018 - 13:00
Köln ist gerade die Foto-Location schlechthin. Während der Photokina finden zahlreiche weitere Events statt. Wir haben recherchiert und zusammengetragen...

Photokina: Huawei: "Nicht die Spiegelreflexkamera ersetzen"

heise online Newsticker - 27. September 2018 - 13:00
Huawei zeigt auf der Photokina erstmals seine Produkte am eigenen Stand. Wir wollten wissen, was sich der Smartphone-Hersteller von der Fotomesse verspricht.

heise-Angebot: JavaLand 2019: Was die Java-Konferenz im nächsten Jahr alles bietet

heise online Newsticker - 27. September 2018 - 13:00
Rund 110 Vorträge und wieder viele Community-Aktivitäten sprechen für ein spannendes und ausgewogenes Programm der Konferenz für Java-Entwickler

Self solving Rubik's cube: Dieser Zauberwürfel löst sich selbst

heise online Newsticker - 27. September 2018 - 13:00
Roboter, die Rubikwürfel drehen, waren gestern: Dieser Würfel erkennt seine Lage und dreht sich selbst wieder zurecht.

Teamarbeit: "Zurücknehmen, um das Ziel zu erreichen"

heise online Newsticker - 27. September 2018 - 13:00
Moderne Mitarbeiter sollen Teamplayer sein, dennoch eigenständig arbeiten. Das ist nur scheinbar ein Widerspruch, erklärt Psychologieprofessor Guido Hertel.

Java 11 bringt nicht nur ein geändertes Supportmodell

heise online Newsticker - 27. September 2018 - 11:30
Zwar bestimmten die geänderten Releasezyklen und Oracles Supportstrategie die Diskussionen bei Java 11, doch auch bei den Features hat sich einiges getan.

Alter Mac Pro: Apple nennt Mojave-kompatible Grafikkarten

heise online Newsticker - 27. September 2018 - 11:30
Apple hat eine Liste mit Grafikkarten veröffentlicht, die alte Profi-Macs im "Käsereibe"-Gehäuse tauglich für macOS 10.14 machen.

Photokina: Fujifilm kündigt spiegellose Systemkamera mit 100 Megapixel-Sensor an

heise online Newsticker - 27. September 2018 - 11:30
Nach Nikon, Canon, Panasonic und Leica bringt nun auch Fujifilm mit der GFX 100 und der GFX 50R frischen Wind in den Bereich der spiegellosen Systemkameras.

Verrat von Geschäftsgeheimnissen: Neue Qualcomm-Vorwürfe gegen Apple

heise online Newsticker - 27. September 2018 - 11:00
Der iPhone-Konzern habe Intel mit geheimen Details über Qualcomms Funkchips weitergeholfen, lautet der Vorwurf.

90 Jahre Motorola: Motorcar traf Ola

heise online Newsticker - 27. September 2018 - 10:30
Ein Autoradio brachte 1930 den Markennamen auf, unter dem die Galvin Manufacturing Corporation ein gutes Stück Geschichte der Mobiltechnik schreiben sollte.

Asperitas kühlt Cloud-Server mit Öl und Wasser

heise online Newsticker - 27. September 2018 - 9:30
Ein niederländisches Startup schickt sich an, die Immersionskühlung zu standardisieren. Auch das Open Compute Project ist daran interessiert.

Astronaut Maurer auf dem Weg ins All: "Weltraum macht süchtig"

heise online Newsticker - 27. September 2018 - 9:30
Während Alexander Gerst in der ISS über der Erde schwebt, bereitet sich am Boden der nächste Deutsche auf seine erste Weltraum-Mission vor: Matthias Maurer.

Mojave: Macs laden großes macOS-Update automatisch im Hintergrund

heise online Newsticker - 27. September 2018 - 9:30
Der über 5 GByte große Installer wird ohne Zutun des Nutzers im Hintergrund heruntergeladen. Dies solle das Upgrade "vereinfachen", so Apple.

Huawei Mate 20 Lite im Test: helles Display, großer Akku

heise online Newsticker - 27. September 2018 - 9:30
Das Huawei Mate 20 Lite ist ein Handy für 399 Euro. Es will großem Display und guter Verarbeitung überzeugen. Ob sich der Kauf lohnt, hat TechStage getestet.

Sicherheitspatch: Angreifer könnten Videoüberwachungssystem von Cisco übernehmen

heise online Newsticker - 27. September 2018 - 9:00
Wichtige Updates schließen Sicherheitslücken in Cisco Video Surveillance Manager und Webex.