PHP generators allow functions to behave like iterators by yielding values one at a time rather than building and returning an array all at once. Generators are automatically created when the yield keyword is used in a function. They implement the Iterator interface and can be used in foreach loops. Data and control flow can be passed into generators using the send() method to influence their behavior.
Design Patterns avec PHP 5.3, Symfony et PimpleHugo Hamon
Cette conférence présente deux grands motifs de conception : l'observateur et l'injection de dépendance. Ce sujet allie à la fois théorie et pratique. Le composant autonome EventDispatcher de Symfony ainsi que le conteneur d'injection de dépendance Pimple sont mis à l'honneur avec des exemples pratiques d'usage. Ces cas pratiques combinent du code de l'ORM Propel ainsi que le composant autonome Zend\Search\Lucene du Zend Framework 2
Slides from presentation on PHP 5.5 Generators given to PHP Brighton group on 16th December 2013, and subsequently to the PHP Cambridge group on 22nd September 2014
PHP 7 – What changed internally? (Forum PHP 2015)Nikita Popov
One of the main selling points of PHP 7 is greatly improved performance, with many real-world applications now running twice as fast… But where do these improvements come from?
At the core of PHP 7 lies an engine rewrite with focus on improving memory usage and performance. This talk provides an overview of the most significant changes, briefly covering everything from data structure changes, over enhancements in the executor, to the new compiler implementation.
Design Patterns avec PHP 5.3, Symfony et PimpleHugo Hamon
Cette conférence présente deux grands motifs de conception : l'observateur et l'injection de dépendance. Ce sujet allie à la fois théorie et pratique. Le composant autonome EventDispatcher de Symfony ainsi que le conteneur d'injection de dépendance Pimple sont mis à l'honneur avec des exemples pratiques d'usage. Ces cas pratiques combinent du code de l'ORM Propel ainsi que le composant autonome Zend\Search\Lucene du Zend Framework 2
Slides from presentation on PHP 5.5 Generators given to PHP Brighton group on 16th December 2013, and subsequently to the PHP Cambridge group on 22nd September 2014
PHP 7 – What changed internally? (Forum PHP 2015)Nikita Popov
One of the main selling points of PHP 7 is greatly improved performance, with many real-world applications now running twice as fast… But where do these improvements come from?
At the core of PHP 7 lies an engine rewrite with focus on improving memory usage and performance. This talk provides an overview of the most significant changes, briefly covering everything from data structure changes, over enhancements in the executor, to the new compiler implementation.
Go beyond the documentation and explore some of what's possible if you stretch symfony to its limits. We will look at a number of aspects of symfony 1.4 and Doctrine 1.2 and tease out some powerful functionality you may not have expected to find, but will doubtless be able to use. Topics covered will include routing, forms, the config cache and record listeners. If you're comfortable in symfony and wondering what's next, this session is for you.
Mirror, mirror on the wall: Building a new PHP reflection library (DPC 2016)James Titcumb
Have you ever used PHP's built in reflection, only to find you can't do quite what you wanted? What about finding types for parameters or properties? What about reflecting on classes that aren't loaded, so that you can modify them directly?
Better Reflection is an awesome new library that uses magical time-warp techniques* (*actual magic or time-warp not guaranteed) to improve on PHP's built-in reflection by providing additional functionality. In this talk we'll cover what reflection is all about, explore the cool features of Better Reflection already implemented, the difficulties we faced actually writing the thing, and how you can use Better Reflection in your projects to maximise your reflection-fu.
Una panoramica su Net::Amazon::EC2 e Net::RackSpace::Servers. Potete trovare la presentazione con le note qui: http://polettix.s3.amazonaws.com/IPW2011/nubilus-perl-1.1-note.pdf
PHP 5.3 and Lithium: the most rad php frameworkG Woo
Presentation given to the Orange County PHP meetup on Feb 24 2010. The presentation covers the new features in php 5.3 and goes on to show how they are used in Lithium, the most rad php framework.
Silex is a brand new PHP 5.3 micro framework built on top of the Symfony2 de decoupled components. In this session, we will discover how to build and deploy powerful REST web services with such a micro framework and its embedded tools.
The first part of this talk will introduce the basics of the REST architecture. We fill focus on the main concepts of REST like HTTP methods, URIs and open formats like XML and JSON.
Then, we will discover how to deploy REST services using most of interesting Silex tools like database abstraction layer, template engine and input validation. We will also look at unit and functional testing frameworks with PHPUnit and HTTP caching with Edge Side Includes and Varnish support to improve performances.
Xlab #1: Advantages of functional programming in Java 8XSolve
Presentation from xlab workshop about functional programming components introduced to the Java 8. How to operate the streams and lambdas in theory and practice.
Slides from the GTA-PHP meetup about the new features in PHP 7. Slides had corresponding RFC pages linked to them in the speaker notes, but they don't seem to correspond to pages here so I've made the original keynote file available at http://gtaphp.org/presentations/NewInPHP7.zip and a PowerPoint version at http://gtaphp.org/presentations/NewInPHP7.pptx.
PHP 7 – What changed internally? (PHP Barcelona 2015)Nikita Popov
One of the main selling points of PHP 7 is greatly improved performance, with many real-world applications now running twice as fast… But where do these improvements come from? At the core of PHP 7 lies an engine rewrite with focus on improving memory usage and performance. This talk provides an overview of the most significant changes, briefly covering everything from data structure changes, over enhancements in the executor, to the new compiler implementation.
Go beyond the documentation and explore some of what's possible if you stretch symfony to its limits. We will look at a number of aspects of symfony 1.4 and Doctrine 1.2 and tease out some powerful functionality you may not have expected to find, but will doubtless be able to use. Topics covered will include routing, forms, the config cache and record listeners. If you're comfortable in symfony and wondering what's next, this session is for you.
Mirror, mirror on the wall: Building a new PHP reflection library (DPC 2016)James Titcumb
Have you ever used PHP's built in reflection, only to find you can't do quite what you wanted? What about finding types for parameters or properties? What about reflecting on classes that aren't loaded, so that you can modify them directly?
Better Reflection is an awesome new library that uses magical time-warp techniques* (*actual magic or time-warp not guaranteed) to improve on PHP's built-in reflection by providing additional functionality. In this talk we'll cover what reflection is all about, explore the cool features of Better Reflection already implemented, the difficulties we faced actually writing the thing, and how you can use Better Reflection in your projects to maximise your reflection-fu.
Una panoramica su Net::Amazon::EC2 e Net::RackSpace::Servers. Potete trovare la presentazione con le note qui: http://polettix.s3.amazonaws.com/IPW2011/nubilus-perl-1.1-note.pdf
PHP 5.3 and Lithium: the most rad php frameworkG Woo
Presentation given to the Orange County PHP meetup on Feb 24 2010. The presentation covers the new features in php 5.3 and goes on to show how they are used in Lithium, the most rad php framework.
Silex is a brand new PHP 5.3 micro framework built on top of the Symfony2 de decoupled components. In this session, we will discover how to build and deploy powerful REST web services with such a micro framework and its embedded tools.
The first part of this talk will introduce the basics of the REST architecture. We fill focus on the main concepts of REST like HTTP methods, URIs and open formats like XML and JSON.
Then, we will discover how to deploy REST services using most of interesting Silex tools like database abstraction layer, template engine and input validation. We will also look at unit and functional testing frameworks with PHPUnit and HTTP caching with Edge Side Includes and Varnish support to improve performances.
Xlab #1: Advantages of functional programming in Java 8XSolve
Presentation from xlab workshop about functional programming components introduced to the Java 8. How to operate the streams and lambdas in theory and practice.
Slides from the GTA-PHP meetup about the new features in PHP 7. Slides had corresponding RFC pages linked to them in the speaker notes, but they don't seem to correspond to pages here so I've made the original keynote file available at http://gtaphp.org/presentations/NewInPHP7.zip and a PowerPoint version at http://gtaphp.org/presentations/NewInPHP7.pptx.
PHP 7 – What changed internally? (PHP Barcelona 2015)Nikita Popov
One of the main selling points of PHP 7 is greatly improved performance, with many real-world applications now running twice as fast… But where do these improvements come from? At the core of PHP 7 lies an engine rewrite with focus on improving memory usage and performance. This talk provides an overview of the most significant changes, briefly covering everything from data structure changes, over enhancements in the executor, to the new compiler implementation.
The quest for global design principles (SymfonyLive Berlin 2015)Matthias Noback
If you’re a programmer you make design decisions every second. You need to think, and often think hard, about everything. Luckily there are many useful design principles and patterns that you can apply. But some of them merely expose code smells. Others only help you design your classes. And some are applicable to packages only. Wouldn’t it be nice to have some more general, always useful, invariably applicable, foundational design principles? In this talk we’ll look at software from many different perspectives, and while we’re zooming in and out, we’ll discover some of the deeper principles that form the basis of proper object-oriented design. After attending this talk you will be able to make better design decisions by reflecting on the stream of messages that is flowing from object to object, and from application to application.
Replacing dependents with doubles is a central part of testing that every developer has to master. This talk goes over the different types of doubles and explains their place in testing, how to implement them in a mainstream mocking framework, and which strategies or doubles to use in different message exchange scenarios between objects. After this talk you will have moved a step forward in your understanding of testing in the context of object oriented programming.
Marcello reflects over the craftsmanship manifesto and its elements to uncover some interesting insights regarding the application of the underlying principles in real life projects and in the context of organisations and communities struggling to live up to the expectations it creates.
Writing infinite scalability web applications with PHP and PostgreSQLGabriele Bartolini
PostgreSQL 9.2 introduced native support for the JSON data type, as well as V8/Javascript and Coffeescript procedural languages.
Learn how you can write web applications in PHP using an intelligent and horizontally sharded cluster of PostgreSQL databases, bringing you infinite scalability and parallel processing.
This talk will guide you through the development lifecycle of the application, focusing on architecture, technologies, testing and deployment.
Si le tdd est mort alors pratiquons une autopsie mix-it 2015Bruno Boucard
Si Michel-Ange avait été développeur quels auraient été ses secrets. Quelle était la posture de cet artiste ? Quelle place occupent nos modèles mentaux lorsque nous développons ? La notion de design émergent qui accompagne les approches test-first (TDD, BDD,…) peut rendre plus d’une personne sceptique. En effet, comment concilier nos intuitions et projections mentales avec cette approche a priori minimaliste et contre-intuitive ?
L'ABC du BDD (Behavior Driven Development)Arnauld Loyer
Une introduction au Behavior Driven Development, avec plein d'idées pour tout de suite! et applicable à tout projet. Il sera question:
* de passer de l'incompréhension à savoir qu'on ne sait pas
* des westerns spaghetti aux Three Amigos,
* de reléguer le Comment au second plan pour laisser sa place au Pourquoi!
* de rendre des spécifications exécutables
* de découvrir qu'un concombre n'est pas qu'un Cucurbitacée aux feuilles tri-lobées
* d'automatisation comme outil de non-regression
Au cours de cette session, nous expliquerons ce qu'est le BDD. Nous verrons qu'il n'est pas question d'outils ou de tests, mais de collaboration et de discussion entre les différentes parties prenantes: du métier aux développeurs en passant par les testeurs. Cette presentation s'adresse à l'ensemble de ces populations en expliquant l'importance qu'il y a à se comprendre, et qu'il n'est pas nécessaire d'avoir des outils sophistiqués pour avoir des bénéfices immédiats.
Nous verrons quelques pratiques de discussion qui permettent d'arriver à une meilleure compréhension et à une description du besoin. Nous verrons aussi comment des exemples concrets permettent de s'assurer d'une compréhension commune et comment ils permettent de construire un langage unique et non ambigu. Nous verrons comment rendre ces spécifications executables en réutilisant les exemples construits précédemment et en les automatisant. Ceux-ci viendront renforcer les tests d'acceptance et devenir des tests de non regressions. Enfin, nous verrons que cette démarche nous permettra d'avoir une documentation vivante et toujours à jour de notre système.
Idées pour tout de suite
Communication, Clarification par des Exemples concrets, Spécifications exécutables
PhpSpec is a SpecBDD tool that enables you to use a TDD workflow that can transform the way you write PHP. In this session we will look at the TDD workflow and see how PhpSpec can be used to speed up your development; add regression safety, and improve your object-oriented design.
The Wonderful World of Symfony ComponentsRyan Weaver
Wow, Symfony Components!
In this talk, we'll look at the history of PHP, and the struggles as a community to create shared libraries between our large community. Find out the significance of PSR-0 and Composer in *your* life and how you can leverage libraries from all of PHP in your projects.
We'll also look at the most fundamental Symfony2 components - HttpFoundation, HttpKernel, EventDispatcher, & Routing - including those that have been adopted by Drupal 8. We'll also check out a bunch of the other interesting Symfony2 components that can be used as tools in any PHP project.
The goal of this talk is to show you just how easy finding and using high quality libraries has become in PHP. By the end, you'll be excited and ready to high-five all of your PHP friends.
This PPT gives the details about Introduction, Syntax, Comments, Case Sensitivity,Variables,Data Types, Strings, Constants,Operators,Control Flow Statements,Functions,Arrays
, and Forms
Php my sql - functions - arrays - tutorial - programmerblog.netProgrammer Blog
In this ppt you will learn about functions and array in php. What are functions, how to declare and use. built in functions. include and required keywords. how are arguments used. how to create functions inside functions.
What are php arrays, how to create an array and use them. Built in array functions. What are super globals?
[PL] Jak nie zostać "programistą" PHP?Radek Benkel
Po sieci krąży wiele opinii, jak to programiści PHP nie są prawdziwymi programistami i że PHP to w ogóle nie jest język programowania, etc.
A winni takiego stanu rzeczy są sami programiści bądź właśnie „programiści”. Dlaczego? W każdym języku da się napisać kod zły jak i dobry. A w świecie PHP niestety dużo jest tego złego – choć trend ten zmienia się na lepsze.
Celem wykładu jest zapoznanie uczestników z rzeczami, na które należy zwrócić uwagę podczas tworzenia aplikacji w języku PHP. Druga (krótsza) część prezentacji będzie poświęcona ogólnym dobrym praktykom programistycznym, nie związanym z żadnym konkretnym językiem.
Drupal enthusiasts in Chennai are coordination with IEEE organized a 3 day workshop. The Workshop introduced Drupal to students. Over 125 students participated this training program.
PHP 8.0 comes with many long-awaited features: A just-in-time compiler, attributes, union types, and named arguments are just a small part of the list. As a major version, it also includes some backward-incompatible changes, which are centered around stricter error handling and enhanced type safety. Let's have an overview of the important changes in PHP 8.0 and how they might affect you!
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.
First Steps with Globus Compute Multi-User EndpointsGlobus
In this presentation we will share our experiences around getting started with the Globus Compute multi-user endpoint. Working with the Pharmacology group at the University of Auckland, we have previously written an application using Globus Compute that can offload computationally expensive steps in the researcher's workflows, which they wish to manage from their familiar Windows environments, onto the NeSI (New Zealand eScience Infrastructure) cluster. Some of the challenges we have encountered were that each researcher had to set up and manage their own single-user globus compute endpoint and that the workloads had varying resource requirements (CPUs, memory and wall time) between different runs. We hope that the multi-user endpoint will help to address these challenges and share an update on our progress here.
How to Position Your Globus Data Portal for Success Ten Good PracticesGlobus
Science gateways allow science and engineering communities to access shared data, software, computing services, and instruments. Science gateways have gained a lot of traction in the last twenty years, as evidenced by projects such as the Science Gateways Community Institute (SGCI) and the Center of Excellence on Science Gateways (SGX3) in the US, The Australian Research Data Commons (ARDC) and its platforms in Australia, and the projects around Virtual Research Environments in Europe. A few mature frameworks have evolved with their different strengths and foci and have been taken up by a larger community such as the Globus Data Portal, Hubzero, Tapis, and Galaxy. However, even when gateways are built on successful frameworks, they continue to face the challenges of ongoing maintenance costs and how to meet the ever-expanding needs of the community they serve with enhanced features. It is not uncommon that gateways with compelling use cases are nonetheless unable to get past the prototype phase and become a full production service, or if they do, they don't survive more than a couple of years. While there is no guaranteed pathway to success, it seems likely that for any gateway there is a need for a strong community and/or solid funding streams to create and sustain its success. With over twenty years of examples to draw from, this presentation goes into detail for ten factors common to successful and enduring gateways that effectively serve as best practices for any new or developing gateway.
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/
Code reviews are vital for ensuring good code quality. They serve as one of our last lines of defense against bugs and subpar code reaching production.
Yet, they often turn into annoying tasks riddled with frustration, hostility, unclear feedback and lack of standards. How can we improve this crucial process?
In this session we will cover:
- The Art of Effective Code Reviews
- Streamlining the Review Process
- Elevating Reviews with Automated Tools
By the end of this presentation, you'll have the knowledge on how to organize and improve your code review proces
A Comprehensive Look at Generative AI in Retail App Testing.pdfkalichargn70th171
Traditional software testing methods are being challenged in retail, where customer expectations and technological advancements continually shape the landscape. Enter generative AI—a transformative subset of artificial intelligence technologies poised to revolutionize software testing.
We describe the deployment and use of Globus Compute for remote computation. This content is aimed at researchers who wish to compute on remote resources using a unified programming interface, as well as system administrators who will deploy and operate Globus Compute services on their research computing infrastructure.
Accelerate Enterprise Software Engineering with PlatformlessWSO2
Key takeaways:
Challenges of building platforms and the benefits of platformless.
Key principles of platformless, including API-first, cloud-native middleware, platform engineering, and developer experience.
How Choreo enables the platformless experience.
How key concepts like application architecture, domain-driven design, zero trust, and cell-based architecture are inherently a part of Choreo.
Demo of an end-to-end app built and deployed on Choreo.
Modern design is crucial in today's digital environment, and this is especially true for SharePoint intranets. The design of these digital hubs is critical to user engagement and productivity enhancement. They are the cornerstone of internal collaboration and interaction within enterprises.
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.
In software engineering, the right architecture is essential for robust, scalable platforms. Wix has undergone a pivotal shift from event sourcing to a CRUD-based model for its microservices. This talk will chart the course of this pivotal journey.
Event sourcing, which records state changes as immutable events, provided robust auditing and "time travel" debugging for Wix Stores' microservices. Despite its benefits, the complexity it introduced in state management slowed development. Wix responded by adopting a simpler, unified CRUD model. This talk will explore the challenges of event sourcing and the advantages of Wix's new "CRUD on steroids" approach, which streamlines API integration and domain event management while preserving data integrity and system resilience.
Participants will gain valuable insights into Wix's strategies for ensuring atomicity in database updates and event production, as well as caching, materialization, and performance optimization techniques within a distributed system.
Join us to discover how Wix has mastered the art of balancing simplicity and extensibility, and learn how the re-adoption of the modest CRUD has turbocharged their development velocity, resilience, and scalability in a high-growth environment.
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.
Why React Native as a Strategic Advantage for Startup Innovation.pdfayushiqss
Do you know that React Native is being increasingly adopted by startups as well as big companies in the mobile app development industry? Big names like Facebook, Instagram, and Pinterest have already integrated this robust open-source framework.
In fact, according to a report by Statista, the number of React Native developers has been steadily increasing over the years, reaching an estimated 1.9 million by the end of 2024. This means that the demand for this framework in the job market has been growing making it a valuable skill.
But what makes React Native so popular for mobile application development? It offers excellent cross-platform capabilities among other benefits. This way, with React Native, developers can write code once and run it on both iOS and Android devices thus saving time and resources leading to shorter development cycles hence faster time-to-market for your app.
Let’s take the example of a startup, which wanted to release their app on both iOS and Android at once. Through the use of React Native they managed to create an app and bring it into the market within a very short period. This helped them gain an advantage over their competitors because they had access to a large user base who were able to generate revenue quickly for them.
top nidhi software solution freedownloadvrstrong314
This presentation emphasizes the importance of data security and legal compliance for Nidhi companies in India. It highlights how online Nidhi software solutions, like Vector Nidhi Software, offer advanced features tailored to these needs. Key aspects include encryption, access controls, and audit trails to ensure data security. The software complies with regulatory guidelines from the MCA and RBI and adheres to Nidhi Rules, 2014. With customizable, user-friendly interfaces and real-time features, these Nidhi software solutions enhance efficiency, support growth, and provide exceptional member services. The presentation concludes with contact information for further inquiries.
Large Language Models and the End of ProgrammingMatt Welsh
Talk by Matt Welsh at Craft Conference 2024 on the impact that Large Language Models will have on the future of software development. In this talk, I discuss the ways in which LLMs will impact the software industry, from replacing human software developers with AI, to replacing conventional software with models that perform reasoning, computation, and problem-solving.
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Shahin Sheidaei
Games are powerful teaching tools, fostering hands-on engagement and fun. But they require careful consideration to succeed. Join me to explore factors in running and selecting games, ensuring they serve as effective teaching tools. Learn to maintain focus on learning objectives while playing, and how to measure the ROI of gaming in education. Discover strategies for pitching gaming to leadership. This session offers insights, tips, and examples for coaches, team leads, and enterprise leaders seeking to teach from simple to complex concepts.
Quarkus Hidden and Forbidden ExtensionsMax Andersen
Quarkus has a vast extension ecosystem and is known for its subsonic and subatomic feature set. Some of these features are not as well known, and some extensions are less talked about, but that does not make them less interesting - quite the opposite.
Come join this talk to see some tips and tricks for using Quarkus and some of the lesser known features, extensions and development techniques.
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.
3. PHP Generators
Wikipedia defines a Generator as:
A generator is very similar to a function that returns an array, in that
a generator has parameters, can be called, and generates a
sequence of values. However, instead of building an array containing
all the values and returning them all at once, a generator yields the
values one at a time, which requires less memory and allows the
caller to get started processing the first few values immediately. In
short, a generator looks like a function but behaves like an iterator.
4. PHP Generators
• Introduced in PHP 5.5
• Iterable (Traversable) Objects
• Can return a series of values, one at a time
• Maintain state between iterations
• Can accept values when sent to the generator
• Similar to enumerators in Ruby, or Sequence Expressions in F#
5. PHP Generators
• Don’t
• Add anything to PHP that couldn’t be done before
• Do
• Allow you to perform iterative operations without an array to iterate
• Potentially reduce memory use
• Potentially faster than iterating over an array
• Can be type-hinted in function/method definitions
• Potentially cleaner and shorter code
• Add semantics to your code
6. PHP Generators
• Automatically created when PHP identifies a function or method
containing the “yield” keyword
function myGeneration() {
yield 1;
}
$generator = myGeneration();
var_dump($generator);
object(Generator)#1 (0) { }
7. PHP Generators
• Implemented as an Object
final class Generator implements Iterator {
mixed current( void );
mixed key( void );
void next( void );
void rewind( void );
mixed send( mixed $value );
mixed throw( Exception $exception );
bool valid( void );
public void __wakeup ( void )
}
• Can’t be extended
10. PHP Generators
foreach (range(0,65535) as $i => $value) {
echo $i , ' -> ' , $value, PHP_EOL;
}
function xrange($lower, $upper) {
for ($i = $lower; $i <= $upper; ++$i) {
yield $i;
}
}
foreach (xrange(0, 65535) as $i => $value) {
echo $i , ' -> ' , $value, PHP_EOL;
}
for($i = 0; $i <= 65535; ++$i) {
echo $i , ' -> ' , $value, PHP_EOL;
}
Time: 0.0183 s
Current Memory: 123.44 k
Peak Memory: 5500.11 k
Time: 0.0135 s
Current Memory: 124.33 k
Peak Memory: 126.84 k
Time: 0.0042 s
Current Memory: 122.92 k
Peak Memory: 124.49 k
11. PHP Generators
function xlColumnRange($lower, $upper) {
++$upper;
for ($i = $lower; $i != $upper; ++$i) {
yield $i;
}
}
foreach (xlColumnRange('A', 'CQ') as $i => $value) {
printf('%3d -> %2s', $i, $value);
echo (($i > 0) && ($i+1 % 5 == 0)) ?
PHP_EOL :
"t";
}
0 -> A 1 -> B 2 -> C 3 -> D 4 -> E
5 -> F 6 -> G 7 -> H 8 -> I 9 -> J
10 -> K 11 -> L 12 -> M 13 -> N 14 -> O
15 -> P 16 -> Q 17 -> R 18 -> S 19 -> T
20 -> U 21 -> V 22 -> W 23 -> X 24 -> Y
25 -> Z 26 -> AA 27 -> AB 28 -> AC 29 -> AD
30 -> AE 31 -> AF 32 -> AG 33 -> AH 34 -> AI
35 -> AJ 36 -> AK 37 -> AL 38 -> AM 39 -> AN
40 -> AO 41 -> AP 42 -> AQ 43 -> AR 44 -> AS
45 -> AT 46 -> AU 47 -> AV 48 -> AW 49 -> AX
50 -> AY 51 -> AZ 52 -> BA 53 -> BB 54 -> BC
55 -> BD 56 -> BE 57 -> BF 58 -> BG 59 -> BH
60 -> BI 61 -> BJ 62 -> BK 63 -> BL 64 -> BM
65 -> BN 66 -> BO 67 -> BP 68 -> BQ 69 -> BR
70 -> BS 71 -> BT 72 -> BU 73 -> BV 74 -> BW
75 -> BX 76 -> BY 77 -> BZ 78 -> CA 79 -> CB
80 -> CC 81 -> CD 82 -> CE 83 -> CF 84 -> CG
85 -> CH 86 -> CI 87 -> CJ 88 -> CK 89 -> CL
90 -> CM 91 -> CN 92 -> CO 93 -> CP 94 -> CQ
12. PHP Generators
$isEven = function ($value) {
return !($value & 1);
};
$isOdd = function ($value) {
return $value & 1;
};
function xFilter(callable $callback, array $args=array()) {
foreach ($args as $arg)
if (call_user_func($callback, $arg))
yield $arg;
}
13. PHP Generators
$data = range(1,10);
echo 'xFilter for Odd Numbers', PHP_EOL;
foreach (xFilter($isOdd, $data) as $i)
echo('num is: '.$i.PHP_EOL);
echo 'xFilter for Even Numbers', PHP_EOL;
foreach (xFilter($isEven, $data) as $i)
echo('num is: '.$i.PHP_EOL);
xFilter for Odd Numbers
num is: 1
num is: 3
num is: 5
num is: 7
num is: 9
xFilter for Even Numbers
num is: 2
num is: 4
num is: 6
num is: 8
num is: 10
14. PHP Generators
• Can return both a value and a “pseudo” key
• By default
• The key is an integer value
• Starting with 0 for the first iteration
• Incrementing by 1 each iteration
• Accessed from foreach() as:
foreach(generator() as $key => $value) {}
• or using
$key = $generatorObject->key();
15. PHP Generators
• Default key behaviour can be changed
• Syntax is:
yield $key => $value;
• Unlike array keys:
• “Pseudo” keys can be any PHP datatype
• “Pseudo” key values can be duplicated
18. PHP Generators
function duplicateKeys($string) {
$string = strtolower($string);
$length = strlen($string);
for ($i = 0; $i < $length; ++$i) {
yield strtoupper($string[$i]) => $string[$i];
}
}
foreach (duplicateKeys('badass') as $key => $value) {
echo $key , ' -> ' , $value, PHP_EOL;
}
B -> b
A -> a
D -> d
A -> a
S -> s
S -> s
20. PHP Generators
• It is possible to access generated values “by reference”
• The generator must be declared “by reference”
• The yielded value must be a variable, and cannot be an expression
22. PHP Generators
• Data can be passed to the generator
• Sometimes called a “Coroutine” when used in this way
• Not strictly accurate, they are more strictly a “Semicoroutine”
• They can form the basis for a “Coroutine” with the addition of a top-level
dispatcher routine
• Syntax is:
$value = yield;
• Calling script uses the “send()” method:
$generatorObject->send($value);
36. PHP Generators
• We can also throw an Exception into a Generator
• A Try/Catch block should be defined in the Generator
• We use the Generator’s “throw()” method from the calling code
$generatorObject->throw(new Exception(‘xyz’));
• Useful for terminating a Generator loop if we don’t want to code a
send() in every iteration
37. PHP Generators
function filteredNumbers(Callable $filter) {
$i = 1;
try {
do {
if (call_user_func($filter, $i)) {
yield $i;
}
} while ($i++ <= PHP_INT_MAX);
} catch (Exception $e) {
echo $e->getMessage(), PHP_EOL;
}
}
39. PHP Generators
• You can’t pass Generators as arguments to array functions
So you can’t call array_map() or array_reduce()with a
Generator instead of an array argument
• But by passing a Generator as an argument to another
Generator, we can chain Generators
Allowing us to simulate array_map() or array_reduce()
49. Who am I?
Mark Baker
Design and Development Manager
InnovEd (Innovative Solutions for Education) Learning Ltd
Coordinator and Developer of:
Open Source PHPOffice library
PHPExcel, PHPWord, PHPPowerPoint, PHPProject, PHPVisio
Minor contributor to PHP core
Other small open source libraries available on github
@Mark_Baker
https://github.com/MarkBaker
http://uk.linkedin.com/pub/mark-baker/b/572/171
http://markbakeruk.net