This DrupalCon 2019 Amsterdam talk provides a look beyond the world of PHP and Javascript. It explores how other languages such as Ruby, Java, Rust and Perl handle things and highlights some interesting features of those languages. Not all the things that other languages can do can be done in PHP or Javascript but the concepts and ideas can still be used.
What should you test with your unit tests? Some people will say that unit behaviour is best tested through it's outcomes. But what if communication between units itself is more important than the results of it? This session will introduce you to two different ways of unit-testing and show you a way to assert your object behaviours through their communications.
From framework coupled code to #microservices through #DDD /by @codelytvCodelyTV
Slides from the talk about our evolution as developers. We start talking about the first spaghetti code that we made and end up talking about which are the differences between:
* Framework coupled code
* DDD modules
* Bounded Contexts
* Microservices
Blog post: http://codely.tv/screencasts/codigo-acoplado-framework-microservicios-ddd
YouTube video (Spanish): https://www.youtube.com/watch?v=o0w-jYun6AU
Twitter: https://twitter.com/CodelyTV
How do you create applications with an incredible level of extendability without losing readability in the process? What if there's a way to separate concerns not only on the code, but on the service definition level? This talk will explore structural and behavioural patterns and ways to enrich them through tricks of powerful dependency injection containers such as Symfony2 DIC component.
What should you test with your unit tests? Some people will say that unit behaviour is best tested through it's outcomes. But what if communication between units itself is more important than the results of it? This session will introduce you to two different ways of unit-testing and show you a way to assert your object behaviours through their communications.
From framework coupled code to #microservices through #DDD /by @codelytvCodelyTV
Slides from the talk about our evolution as developers. We start talking about the first spaghetti code that we made and end up talking about which are the differences between:
* Framework coupled code
* DDD modules
* Bounded Contexts
* Microservices
Blog post: http://codely.tv/screencasts/codigo-acoplado-framework-microservicios-ddd
YouTube video (Spanish): https://www.youtube.com/watch?v=o0w-jYun6AU
Twitter: https://twitter.com/CodelyTV
How do you create applications with an incredible level of extendability without losing readability in the process? What if there's a way to separate concerns not only on the code, but on the service definition level? This talk will explore structural and behavioural patterns and ways to enrich them through tricks of powerful dependency injection containers such as Symfony2 DIC component.
Come to this talk prepared to learn about the Doctrine PHP open source project. The Doctrine project has been around for over a decade and has evolved from database abstraction software that dates back to the PEAR days. The packages provided by the Doctrine project have been downloaded almost 500 million times from packagist. In this talk we will take you through how to get started with Doctrine and how to take advantage of some of the more advanced features.
A lot of people using PHPunit for testing their source code. While I was observing my team
I recognized most of them are only using the standard assertions like 'assertEquals()' or 'assertTrue()' and are complaining about how hard it is to test the code even when the tests are written first. This talk is about all the stuff not used on a daily basis. It shows you some nice features of PHPUnit and how to use them for your benefit.
Un gioco in cui vincono tutti o due piccioni con una fava ;)
Lavorare rivolti alla creazione di valore per il cliente e da questo ottenere una libreria quasi pronta per essere pubblicata
When you move beyond simple snippets of jQuery and start developing more complex interactions, your code can quickly become unwieldy and difficult to debug and maintain. In this presentation, I outline an object-based approach to organizing your jQuery.
Sylius and Api Platform The story of integrationŁukasz Chruściel
Being a part of the Symfony ecosystem gives access to the vast number of open-source solutions built on top. A lot of people voluntarily committed the time to make impressive, multipurpose solutions. One of these solutions is the API Platform, the most mature framework for API development.
In Sylius, it was always our goal to take advantage of the best of the breed and integrate with others. Keeping this in mind, we have decided to combine both projects and deliver a new quality in the headless e-commerce world.
How did it go to integrate new infrastructure to the existing, pretty big codebase? What were the main challenges that we encountered, and how did we solve them? What are the key take-outs from our integrations? I will answer these and a few more questions during this presentation.
Харьковский WordPress MeetUp #2: http://wp.org.ua/?p=191
Какими навыками должен обладать WordPress Гуру (junior, middle, senior) и какие этапы роста проходит WP-разработчик, а также опишет путь от настройки простейшего блога для друга и мелкого фриланса до участия в масштабных Open Source проектах и карьеры в крупной компании. Доклад даст нужное направление для развития новичкам и поможет упорядочить мысли более опытным разработчикам.
Видео будет доступно немного позже.
Come to this talk prepared to learn about the Doctrine PHP open source project. The Doctrine project has been around for over a decade and has evolved from database abstraction software that dates back to the PEAR days. The packages provided by the Doctrine project have been downloaded almost 500 million times from packagist. In this talk we will take you through how to get started with Doctrine and how to take advantage of some of the more advanced features.
A lot of people using PHPunit for testing their source code. While I was observing my team
I recognized most of them are only using the standard assertions like 'assertEquals()' or 'assertTrue()' and are complaining about how hard it is to test the code even when the tests are written first. This talk is about all the stuff not used on a daily basis. It shows you some nice features of PHPUnit and how to use them for your benefit.
Un gioco in cui vincono tutti o due piccioni con una fava ;)
Lavorare rivolti alla creazione di valore per il cliente e da questo ottenere una libreria quasi pronta per essere pubblicata
When you move beyond simple snippets of jQuery and start developing more complex interactions, your code can quickly become unwieldy and difficult to debug and maintain. In this presentation, I outline an object-based approach to organizing your jQuery.
Sylius and Api Platform The story of integrationŁukasz Chruściel
Being a part of the Symfony ecosystem gives access to the vast number of open-source solutions built on top. A lot of people voluntarily committed the time to make impressive, multipurpose solutions. One of these solutions is the API Platform, the most mature framework for API development.
In Sylius, it was always our goal to take advantage of the best of the breed and integrate with others. Keeping this in mind, we have decided to combine both projects and deliver a new quality in the headless e-commerce world.
How did it go to integrate new infrastructure to the existing, pretty big codebase? What were the main challenges that we encountered, and how did we solve them? What are the key take-outs from our integrations? I will answer these and a few more questions during this presentation.
Харьковский WordPress MeetUp #2: http://wp.org.ua/?p=191
Какими навыками должен обладать WordPress Гуру (junior, middle, senior) и какие этапы роста проходит WP-разработчик, а также опишет путь от настройки простейшего блога для друга и мелкого фриланса до участия в масштабных Open Source проектах и карьеры в крупной компании. Доклад даст нужное направление для развития новичкам и поможет упорядочить мысли более опытным разработчикам.
Видео будет доступно немного позже.
Build powerfull and smart web applications with Symfony2Hugo Hamon
Symfony2 first stable release is scheduled for the first week of March 2011. During this session, we will have a look at the new framework architecture and most of its powerfull features.
We will show you how Symfony2 implements the MVC pattern and an HTTP request is processed and converted as a response for the end user. Of course, we will talk about the configuration principles and how it's easy to configure Symfony2 project parts like the routing system or the data model. We will also focus on other major components of the framework like the Doctrine2 integration, forms, security (authentication and authorizations) or HTTP cache management.
Kicking off with Zend Expressive and Doctrine ORM (PHP Srbija 2017)James Titcumb
You've heard of Zend's new framework, Expressive, and you've heard it's the new hotness. In this talk, I will introduce the concepts of Expressive, how to bootstrap a simple application with the framework using best practices, and finally how to integrate a third party tool like Doctrine ORM.
I present four design patterns that make your development easier and better. Design patterns are a fantastic way to make more readable code, as they make use of common ideas that many developers know and use. These patterns are tried and tested in the enterprise world.
The first one is dependency injection. This covers putting the variables that a class needs to function preferably inside a constructor.
The second one is the factory pattern. A factory moves the responsibility of instantiating an object to a third-party class.
The third one is dependency injection. This allows us to place a class' dependencies at one time, making it easy to come back and see what the class needs to survive.
Finally, we discuss the chain of responsibility. This allows complex operations to be handled by a chain of classes. Each class in the chain determines whether it is capable of handling the request and, if so, it returns the result.
Kicking off with Zend Expressive and Doctrine ORM (PHP UK 2017)James Titcumb
You've heard of Zend's new framework, Expressive, and you've heard it's the new hotness. In this talk, I will introduce the concepts of Expressive, how to bootstrap a simple application with the framework using best practices, and finally how to integrate a third party tool like Doctrine ORM.
Kicking off with Zend Expressive and Doctrine ORM (Sunshine PHP 2017)James Titcumb
You've heard of Zend's new framework, Expressive, and you've heard it's the new hotness. In this talk, I will introduce the concepts of Expressive, how to bootstrap a simple application with the framework using best practices, and finally how to integrate a third party tool like Doctrine ORM.
Esta charla comprende las lecciones aprendidas convirtiendo la app de Android de Teambox (una app repleta de deuda técnica y con un alto nivel de acoplamiento entre clases), en la versión actual de Redbooth, que intenta cumplir la arquitectura Hexagonal y los principios SOLID. Durante la exposición explicaremos como fuimos desenredando el código paso a paso; como aplicamos por partes los conceptos de la arquitectura hexagonal; como dejamos de lado componentes del framework de Android que dificultaban el mantenimiento de la app; y que errores cometimos, como los solucionamos y como se podrían haber evitado.
Similar to Multilingualism makes better programmers (20)
Experience our free, in-depth three-part Tendenci Platform Corporate Membership Management workshop series! In Session 1 on May 14th, 2024, we began with an Introduction and Setup, mastering the configuration of your Corporate Membership Module settings to establish membership types, applications, and more. Then, on May 16th, 2024, in Session 2, we focused on binding individual members to a Corporate Membership and Corporate Reps, teaching you how to add individual members and assign Corporate Representatives to manage dues, renewals, and associated members. Finally, on May 28th, 2024, in Session 3, we covered questions and concerns, addressing any queries or issues you may have.
For more Tendenci AMS events, check out www.tendenci.com/events
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERRORTier1 app
Even though at surface level ‘java.lang.OutOfMemoryError’ appears as one single error; underlyingly there are 9 types of OutOfMemoryError. Each type of OutOfMemoryError has different causes, diagnosis approaches and solutions. This session equips you with the knowledge, tools, and techniques needed to troubleshoot and conquer OutOfMemoryError in all its forms, ensuring smoother, more efficient Java applications.
Software Engineering, Software Consulting, Tech Lead.
Spring Boot, Spring Cloud, Spring Core, Spring JDBC, Spring Security,
Spring Transaction, Spring MVC,
Log4j, REST/SOAP WEB-SERVICES.
Cyaniclab : Software Development Agency Portfolio.pdfCyanic lab
CyanicLab, an offshore custom software development company based in Sweden,India, Finland, is your go-to partner for startup development and innovative web design solutions. Our expert team specializes in crafting cutting-edge software tailored to meet the unique needs of startups and established enterprises alike. From conceptualization to execution, we offer comprehensive services including web and mobile app development, UI/UX design, and ongoing software maintenance. Ready to elevate your business? Contact CyanicLab today and let us propel your vision to success with our top-notch IT solutions.
Listen to the keynote address and hear about the latest developments from Rachana Ananthakrishnan and Ian Foster who review the updates to the Globus Platform and Service, and the relevance of Globus to the scientific community as an automation platform to accelerate scientific discovery.
Prosigns: Transforming Business with Tailored Technology SolutionsProsigns
Unlocking Business Potential: Tailored Technology Solutions by Prosigns
Discover how Prosigns, a leading technology solutions provider, partners with businesses to drive innovation and success. Our presentation showcases our comprehensive range of services, including custom software development, web and mobile app development, AI & ML solutions, blockchain integration, DevOps services, and Microsoft Dynamics 365 support.
Custom Software Development: Prosigns specializes in creating bespoke software solutions that cater to your unique business needs. Our team of experts works closely with you to understand your requirements and deliver tailor-made software that enhances efficiency and drives growth.
Web and Mobile App Development: From responsive websites to intuitive mobile applications, Prosigns develops cutting-edge solutions that engage users and deliver seamless experiences across devices.
AI & ML Solutions: Harnessing the power of Artificial Intelligence and Machine Learning, Prosigns provides smart solutions that automate processes, provide valuable insights, and drive informed decision-making.
Blockchain Integration: Prosigns offers comprehensive blockchain solutions, including development, integration, and consulting services, enabling businesses to leverage blockchain technology for enhanced security, transparency, and efficiency.
DevOps Services: Prosigns' DevOps services streamline development and operations processes, ensuring faster and more reliable software delivery through automation and continuous integration.
Microsoft Dynamics 365 Support: Prosigns provides comprehensive support and maintenance services for Microsoft Dynamics 365, ensuring your system is always up-to-date, secure, and running smoothly.
Learn how our collaborative approach and dedication to excellence help businesses achieve their goals and stay ahead in today's digital landscape. From concept to deployment, Prosigns is your trusted partner for transforming ideas into reality and unlocking the full potential of your business.
Join us on a journey of innovation and growth. Let's partner for success with Prosigns.
Into the Box Keynote Day 2: Unveiling amazing updates and announcements for modern CFML developers! Get ready for exciting releases and updates on Ortus tools and products. Stay tuned for cutting-edge innovations designed to boost your productivity.
Globus Compute wth IRI Workflows - GlobusWorld 2024Globus
As part of the DOE Integrated Research Infrastructure (IRI) program, NERSC at Lawrence Berkeley National Lab and ALCF at Argonne National Lab are working closely with General Atomics on accelerating the computing requirements of the DIII-D experiment. As part of the work the team is investigating ways to speedup the time to solution for many different parts of the DIII-D workflow including how they run jobs on HPC systems. One of these routes is looking at Globus Compute as a way to replace the current method for managing tasks and we describe a brief proof of concept showing how Globus Compute could help to schedule jobs and be a tool to connect compute at different facilities.
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...informapgpstrackings
Keep tabs on your field staff effortlessly with Informap Technology Centre LLC. Real-time tracking, task assignment, and smart features for efficient management. Request a live demo today!
For more details, visit us : https://informapuae.com/field-staff-tracking/
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Globus
The Earth System Grid Federation (ESGF) is a global network of data servers that archives and distributes the planet’s largest collection of Earth system model output for thousands of climate and environmental scientists worldwide. Many of these petabyte-scale data archives are located in proximity to large high-performance computing (HPC) or cloud computing resources, but the primary workflow for data users consists of transferring data, and applying computations on a different system. As a part of the ESGF 2.0 US project (funded by the United States Department of Energy Office of Science), we developed pre-defined data workflows, which can be run on-demand, capable of applying many data reduction and data analysis to the large ESGF data archives, transferring only the resultant analysis (ex. visualizations, smaller data files). In this talk, we will showcase a few of these workflows, highlighting how Globus Flows can be used for petabyte-scale climate analysis.
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoamtakuyayamamoto1800
In this slide, we show the simulation example and the way to compile this solver.
In this solver, the Helmholtz equation can be solved by helmholtzFoam. Also, the Helmholtz equation with uniformly dispersed bubbles can be simulated by helmholtzBubbleFoam.
Your Digital Assistant.
Making complex approach simple. Straightforward process saves time. No more waiting to connect with people that matter to you. Safety first is not a cliché - Securely protect information in cloud storage to prevent any third party from accessing data.
Would you rather make your visitors feel burdened by making them wait? Or choose VizMan for a stress-free experience? VizMan is an automated visitor management system that works for any industries not limited to factories, societies, government institutes, and warehouses. A new age contactless way of logging information of visitors, employees, packages, and vehicles. VizMan is a digital logbook so it deters unnecessary use of paper or space since there is no requirement of bundles of registers that is left to collect dust in a corner of a room. Visitor’s essential details, helps in scheduling meetings for visitors and employees, and assists in supervising the attendance of the employees. With VizMan, visitors don’t need to wait for hours in long queues. VizMan handles visitors with the value they deserve because we know time is important to you.
Feasible Features
One Subscription, Four Modules – Admin, Employee, Receptionist, and Gatekeeper ensures confidentiality and prevents data from being manipulated
User Friendly – can be easily used on Android, iOS, and Web Interface
Multiple Accessibility – Log in through any device from any place at any time
One app for all industries – a Visitor Management System that works for any organisation.
Stress-free Sign-up
Visitor is registered and checked-in by the Receptionist
Host gets a notification, where they opt to Approve the meeting
Host notifies the Receptionist of the end of the meeting
Visitor is checked-out by the Receptionist
Host enters notes and remarks of the meeting
Customizable Components
Scheduling Meetings – Host can invite visitors for meetings and also approve, reject and reschedule meetings
Single/Bulk invites – Invitations can be sent individually to a visitor or collectively to many visitors
VIP Visitors – Additional security of data for VIP visitors to avoid misuse of information
Courier Management – Keeps a check on deliveries like commodities being delivered in and out of establishments
Alerts & Notifications – Get notified on SMS, email, and application
Parking Management – Manage availability of parking space
Individual log-in – Every user has their own log-in id
Visitor/Meeting Analytics – Evaluate notes and remarks of the meeting stored in the system
Visitor Management System is a secure and user friendly database manager that records, filters, tracks the visitors to your organization.
"Secure Your Premises with VizMan (VMS) – Get It Now"
SOCRadar Research Team: Latest Activities of IntelBrokerSOCRadar
The European Union Agency for Law Enforcement Cooperation (Europol) has suffered an alleged data breach after a notorious threat actor claimed to have exfiltrated data from its systems. Infamous data leaker IntelBroker posted on the even more infamous BreachForums hacking forum, saying that Europol suffered a data breach this month.
The alleged breach affected Europol agencies CCSE, EC3, Europol Platform for Experts, Law Enforcement Forum, and SIRIUS. Infiltration of these entities can disrupt ongoing investigations and compromise sensitive intelligence shared among international law enforcement agencies.
However, this is neither the first nor the last activity of IntekBroker. We have compiled for you what happened in the last few days. To track such hacker activities on dark web sources like hacker forums, private Telegram channels, and other hidden platforms where cyber threats often originate, you can check SOCRadar’s Dark Web News.
Stay Informed on Threat Actors’ Activity on the Dark Web with SOCRadar!
Enhancing Research Orchestration Capabilities at ORNL.pdfGlobus
Cross-facility research orchestration comes with ever-changing constraints regarding the availability and suitability of various compute and data resources. In short, a flexible data and processing fabric is needed to enable the dynamic redirection of data and compute tasks throughout the lifecycle of an experiment. In this talk, we illustrate how we easily leveraged Globus services to instrument the ACE research testbed at the Oak Ridge Leadership Computing Facility with flexible data and task orchestration capabilities.
Check out the webinar slides to learn more about how XfilesPro transforms Salesforce document management by leveraging its world-class applications. For more details, please connect with sales@xfilespro.com
If you want to watch the on-demand webinar, please click here: https://www.xfilespro.com/webinars/salesforce-document-management-2-0-smarter-faster-better/
Designing for Privacy in Amazon Web ServicesKrzysztofKkol1
Data privacy is one of the most critical issues that businesses face. This presentation shares insights on the principles and best practices for ensuring the resilience and security of your workload.
Drawing on a real-life project from the HR industry, the various challenges will be demonstrated: data protection, self-healing, business continuity, security, and transparency of data processing. This systematized approach allowed to create a secure AWS cloud infrastructure that not only met strict compliance rules but also exceeded the client's expectations.
3. • A look outside of our comfort zone
• Not every example works in PHP/JS
• Concepts/Thought process is still useful
• Examples from Ruby, Java, Rust, Javascript, Perl
About this talk
5. Syntax
The arrangement of words and phrases
to create well-formed sentences in a language
The structure of statements in a computer
language
“ How do I express what I want to do? ”
6. (Standard) Library
A standard library in computer programming
Is the library made available across
Implementations of a programming language.
“ What can I use without installing something else? ”
7. Ecosystem
A collection of software projects, which are developed
and co-evolve in the same environment.
Can be organizational (a company), social (an open-
source community), or technical (the Ruby
ecosystem)
“ What has already been built that I can use? ”
9. The Ruby Styleguide
• A community driven effort to create standards.
• Applicable beyond Ruby
rubocop-hq/ruby-style-guide
10. Keep functions short
Avoid methods longer than 10 LOC (lines of code).
Ideally, most methods will be shorter than 5 LOC.
Empty lines do not contribute to the relevant LOC.
11. Keep functions short
• Give functions a single purpose
• Reduces mental load
• Makes it easier to put the code in presentations ;-)
• Find the right balance
12. function social_post_form_post_form_alter(&$form, FormStateInterface $form_state, $form_id) {
// Show the users picture for new posts.
if ($form_state->getFormObject()->getEntity()->isNew()) {
// Load current user.
$account = User::load(Drupal::currentUser()->id());
// Load compact notification view mode of the attached profile.
if ($account) {
$storage = Drupal::entityTypeManager()->getStorage('profile');
$user_profile = $storage->loadByUser($account, 'profile');
if ($user_profile) {
$content = Drupal::entityTypeManager()->getViewBuilder('profile')
->view($user_profile, 'compact_notification');
// Add to a new field, so twig can render it.
$form['current_user_image'] = $content;
}
}
}
// [Snip]
}
13. function social_post_form_post_form_alter(&$form, FormStateInterface $form_state, $form_id) {
// Show the users picture for new posts.
if ($form_state->getFormObject()->getEntity()->isNew()) {
$user_image = social_post_get_current_user_image();
if ($user_image) {
// Add to a new field, so twig can render it.
$form['current_user_image'] = $user_image;
}
}
// [Snip]
}
14. if as modifier
Prefer modifier if / unless usage when you have a
single-line body.
Another good alternative is the usage of control
flow && / ||.
15. # good (doesn't work in PHP/JS)
do_something if some_condition
# another good option
some_condition && do_something
17. No method_missing
Avoid using method_missing for metaprogramming
because backtraces become messy, the behavior is not
listed in #methods, and misspelled method calls might
silently work, e.g. nukes.luanch_state = false
18. Some of PHPs Magic Methods
• __get, __set, __call
• Used extensively by Drupal
• Can make behaviour less predictable
19. /** Implements the magic method for getting object properties. */
public function &__get($name) {
// If this is an entity field, handle it accordingly. We first check whether
// a field object has been already created. If not, we create one.
if (isset($this->fields[$name][$this->activeLangcode])) {
return $this->fields[$name][$this->activeLangcode];
}
// Inline getFieldDefinition() to speed things up.
if (!isset($this->fieldDefinitions)) { $this->getFieldDefinitions(); }
if (isset($this->fieldDefinitions[$name])) {
$return = $this->getTranslatedField($name, $this->activeLangcode);
return $return;
}
// Else directly read/write plain values. That way, non-field entity
// properties can always be accessed directly.
if (!isset($this->values[$name])) { $this->values[$name] = NULL; }
return $this->values[$name];
}
20. Javascript Proxy
• Emulates PHP’s magic methods
• MDN Documentation
• Could be a talk on its own
• Doesn’t work in Internet Explorer
22. Annotations
In the Java computer programming language, an
annotation is a form of syntactic metadata that can
be added to Java source code.
— Wikipedia, Java_annotation
23. package com.example.examplemod;
import net.minecraft.init.Blocks;
import net.minecraftforge.fml.common.event.FMLInitializationEvent;
public class ExampleMod {
public static final String MODID = "examplemod";
public static final String VERSION = "1.0";
public void init(FMLInitializationEvent event) {
// some example code
System.out.println("DIRT BLOCK >> "+Blocks.dirt.getUnlocalizedName());
}
}
24. package com.example.examplemod;
import net.minecraft.init.Blocks;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.common.event.FMLInitializationEvent;
@Mod(modid = ExampleMod.MODID, version = ExampleMod.VERSION)
public class ExampleMod {
public static final String MODID = "examplemod";
public static final String VERSION = "1.0";
public void init(FMLInitializationEvent event) {
// some example code
System.out.println("DIRT BLOCK >> "+Blocks.dirt.getUnlocalizedName());
}
}
25. package com.example.examplemod;
import net.minecraft.init.Blocks;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.common.Mod.EventHandler;
import net.minecraftforge.fml.common.event.FMLInitializationEvent;
@Mod(modid = ExampleMod.MODID, version = ExampleMod.VERSION)
public class ExampleMod {
public static final String MODID = "examplemod";
public static final String VERSION = "1.0";
@EventHandler
public void init(FMLInitializationEvent event) {
// some example code
System.out.println("DIRT BLOCK >> "+Blocks.dirt.getUnlocalizedName());
}
}
26. namespace DrupalimagePluginFieldFieldWidget;
/**
* Plugin implementation of the 'image_image' widget.
*
* @FieldWidget(
* id = "image_image",
* label = @Translation("Image"),
* field_types = {
* "image"
* }
* )
*/
class ImageWidget extends FileWidget {
// Body omitted
}
27. PHP Annotations
• Not built into the language
• Uses the doctrine/annotations package
• Uses PHP Reflection to read object/method/property comments
• Proposal to move annotations into the PHP runtime (out of
comments). See https://wiki.php.net/rfc/annotations_v2
28. Javascript Annotations Decorators
• Are used to modify the behaviour of a class or its properties
• Are currently a stage 2 proposal
• https://github.com/tc39/proposal-decorators
• Implementation details changed a lot in March 2019
• Babel allows using these already,
as well as the legacy stage 1 syntax.
35. Strongly Typed
In a strongly typed language each data area will
have a distinct type and each process will state its
communication requirements in terms of these
types.
— Jackson, K. (1977).
Design and Implementation of
Programming Languages.
36. Strongly Typed PHP
5.0
5.1
5.4
7.0
7.1
7.4
- Parameter type hints for Interface and Class names
- Parameter type hints for arrays
- Parameter type hints for callables
- Parameter type hints for all primitive types, return type hints
- Nullable types
- Type hints for class properties
37. /* An example of PHP 7.4's type hints. */
class TypeHintsExample {
protected string $chant = 'PHP is improving!';
public function setChant(string $newChant) {
$this->chant = $newChant;
}
public function chant() {
echo $this->chant . PHP_EOL;
}
public function isAwesome() : bool {
return true;
}
}
38. /* An example of PHP 7.4's type hints. */
class TypeHintsExample {
protected string $chant = 'PHP is improving!';
public function setChant(string $newChant) {
$this->chant = $newChant;
}
public function chant() {
echo $this->chant . PHP_EOL;
}
public function isAwesome() : bool {
return true;
}
}
$fan = new TypeHintsExample();
$fan->setChant('PHP is improving!');
// Outputs: "PHP is improving!n"
$fan->chant();
$fan->setChant(9001);
// Outputs: "9001n"
$fan->chant();
39. // Required to actually trigger type errors.
declare(strict_types = 1);
/* An example of PHP 7.4's type hints. */
class TypeHintsExample {
protected string $chant = 'PHP is improving!';
public function setChant(string $newChant) {
$this->chant = $newChant;
}
public function chant() {
echo $this->chant . PHP_EOL;
}
public function isAwesome() : bool {
return true;
}
}
$fan = new TypeHintsExample();
$fan->setChant('PHP is improving!');
// Outputs: "PHP is improving!n"
$fan->chant();
// Throws a TypeError
$fan->setChant(9001);
$fan->chant();
40. Strongly Typed Drupal
• Parameter type hints in coding standards: Issue #1158720
• Standardising array type hints (11 years and counting): Issue #318016
• Discussion about implementing types in existing code: Issue
#3050720
• Highlights some backwards compatibility issues,
some solved in PHP 7.2
• Discussion on coding standard for new code: Issue #3060914
42. Pattern Matching
Patterns are a special syntax in Rust for matching
against the structure of types, both complex and
simple.
43. let x = 1;
match x {
1 => println!("one"),
2 => println!("two"),
3 => println!("three"),
_ => println!("anything"),
}
// Source: https://doc.rust-lang.org/1.5.0/book/patterns.html
44. // PHP
switch ($x) {
case 1:
echo "one";
break;
case 2:
echo "two";
break;
case 3:
echo "three";
break;
default:
echo "anything";
}
// Javascript
switch (x) {
case 1:
console.log("one");
break;
case 2:
console.log("two");
break;
case 3:
console.log("three");
break;
default:
console.log("anything");
}
45. match x {
e @ 1 ... 5 => println!("got a range element {}", e),
i => println!("{} was not in our range", i),
}
46. match x {
e @ 1 ... 5 => println!("got a range element {}", e),
i => println!("{} was not in our range", i),
}
enum OptionalInt {
Value(i32),
Missing,
}
let x = OptionalInt::Value(5);
match x {
OptionalInt::Value(i) if i > 5 => println!("Got an int bigger than five!"),
OptionalInt::Value(..) => println!("Got an int!"),
OptionalInt::Missing => println!("No such luck."),
}
// Source: https://doc.rust-lang.org/1.5.0/book/patterns.html
48. namespace DrupalCoreLanguage;
/**
* Defines a language.
*/
interface LanguageInterface {
// [Snip]
/**
* Language written left to right.
* Possible value of $language->direction.
*/
const DIRECTION_LTR = 'ltr';
/**
* Language written right to left.
* Possible value of $language->direction.
*/
const DIRECTION_RTL = 'rtl';
/**
* Gets the text direction (left-to-right or
* right-to-left).
*
* @return string
* Either self::DIRECTION_LTR
* or self::DIRECTION_RTL.
*/
public function getDirection();
// [Snip]
}
49. /**
* Defines a language.
*/
interface LanguageInterface {
// [Snip]
/**
* Gets the text direction
* (left-to-right or right-to-left).
*
* @return string
* Either self::DIRECTION_LTR
* or self::DIRECTION_RTL.
*/
public function getDirection();
}
50. class Gibberish implements LanguageInterface {
// Required methods omitted for brevity.
public function getDirection() {
return 'outside-in';
}
}
/**
* Defines a language.
*/
interface LanguageInterface {
// [Snip]
/**
* Gets the text direction
* (left-to-right or right-to-left).
*
* @return string
* Either self::DIRECTION_LTR
* or self::DIRECTION_RTL.
*/
public function getDirection();
}
53. // Create an `enum` to classify a web event. Note how both
// names and type information together specify the variant:
// `PageLoad != PageUnload` and `KeyPress(char) != Paste(String)`.
// Each is different and independent.
enum WebEvent {
// An `enum` may either be `unit-like`,
PageLoad,
PageUnload,
// like tuple structs,
KeyPress(char),
Paste(String),
// or like structures.
Click { x: i64, y: i64 },
}
// Source https://doc.rust-lang.org/stable/rust-by-example/custom_types/enum.html
54. PHP
• No support out of the box
• SPL (Standard PHP Library) Types extension exists
• Careful: it's experimental
• Check your return values manually
56. NULL does not exist
Error: Call to a member function someFunction() on null
57. /**
* Loads an entity.
*
* @param mixed $id
* The id of the entity to load.
*
* @return static
* The entity object or NULL if there is no entity with the given ID.
*/
// Given we have < 9000 nodes.
// Throws: Error: Call to a member function label() on null
Node::load(9002)->label();
58. use std::fs::File;
use std::io::prelude::*;
fn main() {
let file = File::open("foo.txt");
let mut contents = String::new();
file.read_to_string(&mut contents);
println!("The contents of the file: {}", contents);
}
59.
60. Error handling with the Result type
Result<T, E> is the type used for returning and
propagating errors.
It is an enum with the variants, Ok(T), representing
success and containing a value, and Err(E),
representing error and containing an error value.
67. function init() {
var name = 'Mozilla'; // name is a local variable created by init
function displayName() { // displayName() is the inner function, a closure
console.log(name); // use variable declared in the parent function
}
displayName();
}
// Outputs: Mozilla
init();
// Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures
68. function makeFunc() {
var name = 'Mozilla';
function displayName() {
console.log(name);
}
return displayName;
}
var myFunc = makeFunc();
// Outputs: Mozilla
myFunc();
// Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures
69. function addFunction (x) {
return x + 5;
}
const addArrowFn = x => x + 5;
console.log(addFunction(2)); // 7
console.log(addArrowFn(2)); // 7
70. function makeAdder(x) {
return y => x + y;
}
const add6 = makeAdder(6);
const add9 = makeAdder(9);
console.log(add6(9)); // 14
console.log(add9(9)); // 18
71. Functional Programming
In computer science, functional programming is a
programming paradigm that treats computation as
the evaluation of mathematical functions and avoids
changing-state and mutable data.
— Wikipedia, Functional_programming
78. Schwartzian Transform
In computer programming, the Schwartzian
transform is a technique used to improve the
efficiency of sorting a list of items.
79. Schwartzian Transform
• Sorting based on a certain property
• Calculating that property is expensive
• e.g. sort orders based on total value
• Can work without intermediate variables
• It’s possible in PHP but horrible.
• A Javascript example is simpler
80. const unsorted = [2, 0, 5, 3, 1, 4];
let seen = [0, 0, 0, 0, 0, 0];
// Copy the array and sort it. Count the
// number of times each item is compared.
const sorted = unsorted.slice().sort(
(a, b) => {
seen[a]++;
seen[b]++;
return a - b;
}
);
console.log("NumbertTimes seen");
seen.forEach((times, number) => {
console.log(`${number}t${times}`);
});
Number
0
1
2
3
4
5
Times seen
3
3
5
4
3
4
81. // slowTransform: wait 1s and return x * 2.
const unsorted = [2, 0, 5, 3, 1, 4];
// Copy the array and sort it.
const sorted = unsorted.slice().sort(
(a, b) => {
// Access network, disk, calculate prime number or fibonacci.
return slowTransform(a) - slowTransform(b);
}
);
// [ 0, 1, 2, 3, 4, 5 ]
console.log(sorted);
// Takes about 22 seconds.
82. // slowTransform: wait 1s and return x * 2.
const unsorted = [2, 0, 5, 3, 1, 4];
// Copy the array, transform, then sort.
const sorted = unsorted.slice()
.map(slowTransform)
.sort(
(a, b) => {
return a - b;
}
);
// [ 0, 2, 4, 6, 8, 10 ]
console.log(sorted);
// Takes about 6 seconds.
86. Thank you! Questions?
Slides: tiny.cc/dc2019slides
Snippets: tiny.cc/dc2019code
Locate this session at the DrupalCon Amsterdam website:
https://drupal.kuoni-congress.info/2019/program/
Take the Survey!
https://www.surveymonkey.com/r/DrupalConAmsterdam
87. Join us for
contribution opportunities
Thursday, October 31, 2019
9:00-18:00
Room: Europe Foyer 2
Mentored
Contribution
First Time
Contributor Workshop
General
Contribution
#DrupalContributions
9:00-14:00
Room: Diamond Lounge
9:00-18:00
Room: Europe Foyer 2