The document discusses PHP enums introduced in PHP 8.1. It begins by providing examples of why enums are needed, such as for defining valid options for functions like curl_setopt() and representing statuses. It then covers how enums can help by enforcing valid values, allowing stronger typing, and avoiding bugs. The remainder of the document dives into details of enums in PHP 8.1, including the differences between unit enums and backed enums, and semantics like enums being fixed types that cannot contain state.
The document discusses PHP 8.1 enums, including why enums are needed, how they can help, how enums work in PHP 8.1, and examples of using enums. Key points include: enums allow for stronger typing than constants, make invalid values impossible, and improve code readability and maintainability. Enums in PHP 8.1 can have zero or more members, members are objects, and enums can be namespaced and autoloaded.
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
This session introduces most well known design patterns to build PHP classes and objects that need to store and fetch data from a relational databases. The session will describe the difference between of the Active Record, the Table and Row Data Gateway and the Data Mapper pattern. We will also examine some technical advantages and drawbacks of these implementations. This talk will expose some of the best PHP tools, which ease database interactions and are built on top of these patterns.
The document discusses the architecture of a shopping cart system and how to make it easily testable and extensible. It recommends separating the core logic from session and database handling, and making frequently changing features into plugins. It also suggests simplifying the structure for easier testing by using storage instead of sessions, and DAO instead of databases during tests. The storage abstraction layer is implemented to operate on different mediums like arrays or sessions.
This document summarizes the history of PHP persistence from 1995 to present day. It begins with early file handling in PHP/FI in 1995 and the introduction of database support. It then discusses the evolution of code reusability through functions and classes. Professional abstraction layers like PEAR and later ORM frameworks provided more robust and standardized APIs. NoSQL databases and drivers were later incorporated, moving beyond relational databases. Current frameworks provide object document mapping for non-SQL databases like MongoDB.
The document contains code for unit testing a PHP MVC application using PHPUnit. It includes:
- Code for the Todo model and its tests using PHPUnit assertions.
- Configuration for PHPUnit to run tests for the application and library.
- Tests for the IndexController using a Test_ControllerTestCase class with helper methods.
- Code for Request, Response and View classes to mock the MVC framework.
- A test to interact with the application interface using Selenium.
The document shows the project structure for an MVC application and library with tests. It demonstrates how to test models, controllers and the user interface using test doubles, assertions and helper methods in PHPUnit.
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.
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
The document discusses PHP 8.1 enums, including why enums are needed, how they can help, how enums work in PHP 8.1, and examples of using enums. Key points include: enums allow for stronger typing than constants, make invalid values impossible, and improve code readability and maintainability. Enums in PHP 8.1 can have zero or more members, members are objects, and enums can be namespaced and autoloaded.
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
This session introduces most well known design patterns to build PHP classes and objects that need to store and fetch data from a relational databases. The session will describe the difference between of the Active Record, the Table and Row Data Gateway and the Data Mapper pattern. We will also examine some technical advantages and drawbacks of these implementations. This talk will expose some of the best PHP tools, which ease database interactions and are built on top of these patterns.
The document discusses the architecture of a shopping cart system and how to make it easily testable and extensible. It recommends separating the core logic from session and database handling, and making frequently changing features into plugins. It also suggests simplifying the structure for easier testing by using storage instead of sessions, and DAO instead of databases during tests. The storage abstraction layer is implemented to operate on different mediums like arrays or sessions.
This document summarizes the history of PHP persistence from 1995 to present day. It begins with early file handling in PHP/FI in 1995 and the introduction of database support. It then discusses the evolution of code reusability through functions and classes. Professional abstraction layers like PEAR and later ORM frameworks provided more robust and standardized APIs. NoSQL databases and drivers were later incorporated, moving beyond relational databases. Current frameworks provide object document mapping for non-SQL databases like MongoDB.
The document contains code for unit testing a PHP MVC application using PHPUnit. It includes:
- Code for the Todo model and its tests using PHPUnit assertions.
- Configuration for PHPUnit to run tests for the application and library.
- Tests for the IndexController using a Test_ControllerTestCase class with helper methods.
- Code for Request, Response and View classes to mock the MVC framework.
- A test to interact with the application interface using Selenium.
The document shows the project structure for an MVC application and library with tests. It demonstrates how to test models, controllers and the user interface using test doubles, assertions and helper methods in PHPUnit.
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.
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
Adding Dependency Injection to Legacy ApplicationsSam Hennessy
Dependency Injection (DI) is a fantastic technique, but what if you what to use dependency injection in your legacy application. Fear not! As someone who as done this very thing, I will show how you can successful and incrementally add DI to any application. I will present a number of recipes and solutions to common problems and give a tour of the various PHP DI projects and how they can help.
This document defines PHP functions for handling communication channels, packet encoding/decoding, and core commands for a remote access tool or backdoor. It establishes global variables to track open channels and commands. Functions are defined to open, read, write, close and interact with channels. It also implements encoding of requests/responses with XOR encryption and random IDs.
How do you measure the quality of your code? Performance and testing are just one aspect of code, in order to meet deadlines and make maintenance quicker you also need your code to be readable, decoupled and generally easier to comprehend and work with. This talk will go over tips and exercises to help you identify trouble areas, refactor them and train you to write better code in future projects. Come make your code look and function better.
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.
This document discusses using Doctrine fixtures and the Faker library to generate fake test data for entities in a Symfony application. It explains how to install and configure Doctrine fixtures bundles, structure fixture classes, and load fixtures. It then covers installing and using the Faker library to generate random names, addresses, phone numbers and more. It provides examples of localizing Faker, seeding values, and generating unique or optional values. The document concludes by discussing using Faker to populate ORM entities and customizing population values.
This document provides an overview and examples of several design patterns in object-oriented programming with PHP, including Strategy, Factory, Abstract Factory, Adapter, Singleton, Iterator, and Observer patterns. The Strategy pattern allows making decisions on different cases more easily by encapsulating varying implementations of an algorithm. The Factory pattern hides object creation logic and allows for polymorphic object instantiation. The Abstract Factory pattern ensures all created objects conform to a common interface. The Adapter pattern allows incompatible interfaces to work together by wrapping an object to fit expected interfaces. The Singleton pattern ensures only one instance of a class is created. The Iterator pattern provides a way to access elements of an object sequentially without exposing its underlying representation. The Observer pattern allows objects to publish
Symfony World - Symfony components and design patternsŁukasz Chruściel
There are so many Symfony components already, and they have some pretty neat perks. But have you seen them in action?
Design patterns are not a silver bullet. They will never resolve your problem on their own. On the other hand, design patterns provide a common ground for developers without going into details and could be used as building bricks to solve some more advanced problems.
During my presentation, I will take a closer look and explain the appliance of selected design patterns. What is more, I will take advantage of the Symfony ecosystem to implement them with ease.
I will do the presentation on sample code that developers will understand at all levels of expertise.
The document discusses dependency injection containers and configuration in frameworks. It provides examples of configuring services like mail transport and mailers using different approaches like procedural code, object-oriented code, and XML configuration. It also discusses managing configuration for different environments and making components more flexible through inheritance and customization.
Rich domain model with symfony 2.5 and doctrine 2.5Leonardo Proietti
This document summarizes a presentation on building a rich domain model with Symfony2 and Doctrine2. It discusses modeling the domain by focusing on the problem space rather than the solution space. It emphasizes making the domain model ubiquitous by using a common language throughout the code and contexts. The presentation also covers using entities as both domain objects and persistence model objects, validating inputs and protecting invariants, and taking an iterative test-driven approach to developing the domain model.
This talk is an overview of the history of the PHP language and major framework projects that have emerged in the last 5 years. It examines what we've learned in the development of these frameworks, how that education has been brought to bear in Lithium. Most of this talk ended up being me demoing and answering questions, so there's not a lot of content in the slides, sorry.
The IoC Hydra - Dutch PHP Conference 2016Kacper Gunia
Slides from my talk presented during Dutch PHP Conference in Amsterdam - 25 June 2016
More Domain-Driven Design related content at: https://domaincentric.net/
This document contains a summary of jQuery secrets presented by Bastian Feder. It discusses various techniques including saving and removing state from DOM elements using jQuery.data() and jQuery.removeData(), extending jQuery functionality through plugins, and customizing AJAX requests and event handling. The presentation provides code examples for working with jQuery's data storage methods, namespaces, promises/deferreds, global AJAX settings, and extending jQuery.
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()' 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 and it digs deep into uncommon features of PHPUnit.
PHP for Adults: Clean Code and Object CalisthenicsGuilherme Blanco
The document discusses principles and techniques for writing clean code in PHP, including:
- The S.O.L.I.D. principles for object-oriented design (single responsibility, open/closed, Liskov substitution, etc.)
- Object calisthenics rules for PHP functions/methods like using single indentation levels and early returns.
- Refactoring code examples to follow these principles and rules to improve readability, maintainability and testability of PHP code.
Rich Model And Layered Architecture in SF2 ApplicationKirill Chebunin
Presentation for Symfony Camp UA 2012.
* What are Rich Model, Service Layer & Layered Architecture
* Layered architecture in Sf2 Application
* Integration with 3rd party bundles
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.
This document discusses the Symfony framework and its components. It introduces the Symfony philosophy of being easy for newcomers and flexible for advanced users. It then summarizes several Symfony components like CssSelector, DomCrawler, Finder, and the HttpKernel interface. It concludes by asking if there are any questions.
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.
Speed up your developments with Symfony2Hugo Hamon
Symfony2 is a PHP full-stack framework that provides tools and components to speed up web development. It emphasizes separation of concerns, standards compliance, and best practices. Symfony2 allows developers to create Request-Response applications using its routing, templating, validation, forms, database abstraction, and other features in a decoupled and reusable way. It also provides debugging tools, code generators, and other utilities to improve developer productivity.
PHP 8.1 brings Enums, one of the most requested features in PHP.
Enums, or Enumerations, allow creating strict and type-safe structures for fixed values. An Enum structure can hold a number of values that can also be backed with integer or string values.
In this comprehensive session, we will discover what Enums are, why they are useful, how to apply them on our applications, and things to watch out for when using Enums.
The REST API is an awesome plugin to expose your data from the WordPress core. But … the standard implementation might not fit your specific case.
Just like the WordPress core, you'll be able to extend it to your specific needs. I'll show you how to handle authentication, introduce caching strategies, alter custom post types, or even change the default way of communication altogether.
Adding Dependency Injection to Legacy ApplicationsSam Hennessy
Dependency Injection (DI) is a fantastic technique, but what if you what to use dependency injection in your legacy application. Fear not! As someone who as done this very thing, I will show how you can successful and incrementally add DI to any application. I will present a number of recipes and solutions to common problems and give a tour of the various PHP DI projects and how they can help.
This document defines PHP functions for handling communication channels, packet encoding/decoding, and core commands for a remote access tool or backdoor. It establishes global variables to track open channels and commands. Functions are defined to open, read, write, close and interact with channels. It also implements encoding of requests/responses with XOR encryption and random IDs.
How do you measure the quality of your code? Performance and testing are just one aspect of code, in order to meet deadlines and make maintenance quicker you also need your code to be readable, decoupled and generally easier to comprehend and work with. This talk will go over tips and exercises to help you identify trouble areas, refactor them and train you to write better code in future projects. Come make your code look and function better.
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.
This document discusses using Doctrine fixtures and the Faker library to generate fake test data for entities in a Symfony application. It explains how to install and configure Doctrine fixtures bundles, structure fixture classes, and load fixtures. It then covers installing and using the Faker library to generate random names, addresses, phone numbers and more. It provides examples of localizing Faker, seeding values, and generating unique or optional values. The document concludes by discussing using Faker to populate ORM entities and customizing population values.
This document provides an overview and examples of several design patterns in object-oriented programming with PHP, including Strategy, Factory, Abstract Factory, Adapter, Singleton, Iterator, and Observer patterns. The Strategy pattern allows making decisions on different cases more easily by encapsulating varying implementations of an algorithm. The Factory pattern hides object creation logic and allows for polymorphic object instantiation. The Abstract Factory pattern ensures all created objects conform to a common interface. The Adapter pattern allows incompatible interfaces to work together by wrapping an object to fit expected interfaces. The Singleton pattern ensures only one instance of a class is created. The Iterator pattern provides a way to access elements of an object sequentially without exposing its underlying representation. The Observer pattern allows objects to publish
Symfony World - Symfony components and design patternsŁukasz Chruściel
There are so many Symfony components already, and they have some pretty neat perks. But have you seen them in action?
Design patterns are not a silver bullet. They will never resolve your problem on their own. On the other hand, design patterns provide a common ground for developers without going into details and could be used as building bricks to solve some more advanced problems.
During my presentation, I will take a closer look and explain the appliance of selected design patterns. What is more, I will take advantage of the Symfony ecosystem to implement them with ease.
I will do the presentation on sample code that developers will understand at all levels of expertise.
The document discusses dependency injection containers and configuration in frameworks. It provides examples of configuring services like mail transport and mailers using different approaches like procedural code, object-oriented code, and XML configuration. It also discusses managing configuration for different environments and making components more flexible through inheritance and customization.
Rich domain model with symfony 2.5 and doctrine 2.5Leonardo Proietti
This document summarizes a presentation on building a rich domain model with Symfony2 and Doctrine2. It discusses modeling the domain by focusing on the problem space rather than the solution space. It emphasizes making the domain model ubiquitous by using a common language throughout the code and contexts. The presentation also covers using entities as both domain objects and persistence model objects, validating inputs and protecting invariants, and taking an iterative test-driven approach to developing the domain model.
This talk is an overview of the history of the PHP language and major framework projects that have emerged in the last 5 years. It examines what we've learned in the development of these frameworks, how that education has been brought to bear in Lithium. Most of this talk ended up being me demoing and answering questions, so there's not a lot of content in the slides, sorry.
The IoC Hydra - Dutch PHP Conference 2016Kacper Gunia
Slides from my talk presented during Dutch PHP Conference in Amsterdam - 25 June 2016
More Domain-Driven Design related content at: https://domaincentric.net/
This document contains a summary of jQuery secrets presented by Bastian Feder. It discusses various techniques including saving and removing state from DOM elements using jQuery.data() and jQuery.removeData(), extending jQuery functionality through plugins, and customizing AJAX requests and event handling. The presentation provides code examples for working with jQuery's data storage methods, namespaces, promises/deferreds, global AJAX settings, and extending jQuery.
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()' 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 and it digs deep into uncommon features of PHPUnit.
PHP for Adults: Clean Code and Object CalisthenicsGuilherme Blanco
The document discusses principles and techniques for writing clean code in PHP, including:
- The S.O.L.I.D. principles for object-oriented design (single responsibility, open/closed, Liskov substitution, etc.)
- Object calisthenics rules for PHP functions/methods like using single indentation levels and early returns.
- Refactoring code examples to follow these principles and rules to improve readability, maintainability and testability of PHP code.
Rich Model And Layered Architecture in SF2 ApplicationKirill Chebunin
Presentation for Symfony Camp UA 2012.
* What are Rich Model, Service Layer & Layered Architecture
* Layered architecture in Sf2 Application
* Integration with 3rd party bundles
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.
This document discusses the Symfony framework and its components. It introduces the Symfony philosophy of being easy for newcomers and flexible for advanced users. It then summarizes several Symfony components like CssSelector, DomCrawler, Finder, and the HttpKernel interface. It concludes by asking if there are any questions.
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.
Speed up your developments with Symfony2Hugo Hamon
Symfony2 is a PHP full-stack framework that provides tools and components to speed up web development. It emphasizes separation of concerns, standards compliance, and best practices. Symfony2 allows developers to create Request-Response applications using its routing, templating, validation, forms, database abstraction, and other features in a decoupled and reusable way. It also provides debugging tools, code generators, and other utilities to improve developer productivity.
PHP 8.1 brings Enums, one of the most requested features in PHP.
Enums, or Enumerations, allow creating strict and type-safe structures for fixed values. An Enum structure can hold a number of values that can also be backed with integer or string values.
In this comprehensive session, we will discover what Enums are, why they are useful, how to apply them on our applications, and things to watch out for when using Enums.
The REST API is an awesome plugin to expose your data from the WordPress core. But … the standard implementation might not fit your specific case.
Just like the WordPress core, you'll be able to extend it to your specific needs. I'll show you how to handle authentication, introduce caching strategies, alter custom post types, or even change the default way of communication altogether.
This document discusses PHPSpec, a behavior-driven development (BDD) framework for PHP. It begins by explaining what PHPSpec is and how it implements BDD through a domain-specific language (DSL) based on RSpec. The document then covers how PHPSpec specifies tests using contexts, examples, expectations, matchers, mocks, and stubs. It provides examples of writing PHPSpec tests and using various PHPSpec features. The document concludes by mentioning upcoming PHPSpec features and linking to resources for learning more.
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.
This is a "PHP 201" presentation that was given at the December 2010 Burlington, Vermont PHP Users group meeting. Going beyond the basics, this presentation covered working with arrays, functions, and objects.
The REST API is an awesome plugin to expose your data from the WordPress core. But … the standard implementation might not fit your specific case.
Just like the WordPress core, you'll be able to extend it to your specific needs. I'll show you how to handle authentication, introduce caching strategies, alter custom post types, or even change the default way of communication altogether.
Why is crud a bad idea - focus on real scenariosDivante
This document discusses why CRUD (Create, Read, Update, Delete) is generally not a good approach for designing application code and APIs. It argues that entities should follow real business rules and scenarios rather than allowing arbitrary setting of attributes. Setters in particular are problematic as they don't map to real-world actions and don't enforce data integrity. The document recommends focusing on expressive methods that model real use cases rather than generic update operations. It also discusses how to add a CRUD layer on top of an internal domain model if needed while still maintaining encapsulation. The key takeaway is that applications should be designed around rich domain objects and real business behaviors rather than simple data access patterns.
Type hints were introduced with PHP 5. PHP 7 will add the ability to type hint on scalars and even to explicitly state what type will be returned from the function. This talk briefly goes over these added features to PHP 7.
Building Lithium Apps (Like a Boss) was a workshop presented on the structure and philosophy of the Lithium framework and its applications, and how best to take advantage of them.
This document discusses using PHP to build rich internet applications (RIAs). It provides examples of using PHP to return XML or JSON data to an RIA client, and using AMFPHP to transfer PHP objects directly to ActionScript clients. It recommends building PHP apps as services that can be consumed by any front-end technology, including Ajax, XAML and Flex, in order to simplify the PHP code.
This document discusses building REST APIs with Laravel 5. It covers topics like using REST instead of SOAP, authentication with basic authentication and middleware, response formats, controller hierarchy, repositories, data transformers, error handling, and an internal dispatcher for making internal API requests. The goal is to provide best practices and patterns for building robust and well-structured REST APIs with Laravel.
[PHPCon 2023] “Kto to pisał?!... a, to ja.”, czyli sposoby żeby znienawidzić ...Mateusz Zalewski
Czysty kod. Jakościowe oprogramowanie. Dobre praktyki. Święte Graale pracy programisty, o których każdy z nas wie, a mimo to wciąż zachowujemy się tak, jakby ich nie było. Bo przecież ten kod to tylko na chwilę. A tego to w ogóle nie będziemy używać. A tę klasę się zrefaktoruje później. Wszyscy od czasu do czasu zaciągamy dług u samych z siebie z przyszłości - dług, którego potem (nie bez powodu) bardzo nie chcemy spłacać.
Zagłębmy się więc w ten fascynujący świat słabego oprogramowania. Przejdźmy przez las nieużytych wzorców projektowych, przebrnijmy przez bagna zagnieżdżonych pętli. Wejdźmy na kolejny ośmiotysięcznik, a może z jego szczytu uda nam się dojrzeć zatokę pięknego kodu - w której, miejmy nadzieję, tym razem pozostaniemy na dłużej.
The document discusses the SOLID principles of object-oriented design:
- The Single Responsibility Principle states that a class should have one, and only one, reason to change. An example class that violates this principle is refactored to separate concerns into distinct classes.
- The Open/Closed Principle states that a class should be open for extension but closed for modification. An encoder class is refactored to use polymorphism and dependency injection to follow this principle.
- The Liskov Substitution Principle states that subclasses must be substitutable for their base classes. Examples of violations include subclasses not implementing base class methods or having incompatible method signatures.
This document provides an overview of PHP including:
- Basic PHP syntax like variables, data types, operators, and control structures
- Functions - both built-in and user-defined, including arguments and return values
- Loops - while, do-while, for, foreach
- Object-oriented concepts like classes, objects, constructors, inheritance
- Arrays - indexed, associative, and multidimensional
- Strings and math functions
- An introduction to abstraction and object-oriented programming principles in PHP
The document discusses the Standard PHP Library (SPL) which provides standard interfaces, classes, and functions for common programming problems. It summarizes key SPL components like autoloading classes using spl_autoload_register(), iterators for arrays and directories, and interfaces like ArrayAccess, Iterator, and Countable. The Observer pattern implementation using SplSubject and SplObserver is also covered.
This document summarizes Benjamin Eberlei's talk on using Doctrine to interact with databases in PHP applications. Doctrine provides an object relational mapper (ORM) and database abstraction layer (DBAL) that allow developers to work with various database systems in a consistent way. The DBAL component handles driver abstraction, SQL dialects, convenience APIs, SQL types and database schema handling to simplify common database tasks.
You Don't Know Query (WordCamp Netherlands 2012)andrewnacin
An update to a talk I gave at WordCamp Portland 2011, "You Don't Know Query" is an advanced development talk from March 25, 2012, in Utrecht, Netherlands.
This document summarizes some new features in PHP 5.4:
- Array syntax can now be written more concisely using square brackets instead of array functions.
- PHP 5.4 includes a built-in web server for development purposes, allowing PHP scripts to be run without Apache.
- Traits allow sharing of methods across classes to reduce code duplication, similar to mixins in Ruby.
- Closures now support accessing properties of the enclosing class scope via $this.
Internationalizing CakePHP ApplicationsPierre MARTIN
The document discusses internationalization in CakePHP, including:
- Using methods like __() and __n() to translate text strings, and Configure::write() to set the application language.
- The Translate behavior, which allows translating database records into multiple languages and automatically filtering by the current language.
- Generating translation files using the i18n extractor, editing them with POEDIT, and caching translated elements.
Full-RAG: A modern architecture for hyper-personalizationZilliz
Mike Del Balso, CEO & Co-Founder at Tecton, presents "Full RAG," a novel approach to AI recommendation systems, aiming to push beyond the limitations of traditional models through a deep integration of contextual insights and real-time data, leveraging the Retrieval-Augmented Generation architecture. This talk will outline Full RAG's potential to significantly enhance personalization, address engineering challenges such as data management and model training, and introduce data enrichment with reranking as a key solution. Attendees will gain crucial insights into the importance of hyperpersonalization in AI, the capabilities of Full RAG for advanced personalization, and strategies for managing complex data integrations for deploying cutting-edge AI solutions.
Taking AI to the Next Level in Manufacturing.pdfssuserfac0301
Read Taking AI to the Next Level in Manufacturing to gain insights on AI adoption in the manufacturing industry, such as:
1. How quickly AI is being implemented in manufacturing.
2. Which barriers stand in the way of AI adoption.
3. How data quality and governance form the backbone of AI.
4. Organizational processes and structures that may inhibit effective AI adoption.
6. Ideas and approaches to help build your organization's AI strategy.
OpenID AuthZEN Interop Read Out - AuthorizationDavid Brossard
During Identiverse 2024 and EIC 2024, members of the OpenID AuthZEN WG got together and demoed their authorization endpoints conforming to the AuthZEN API
Unlocking Productivity: Leveraging the Potential of Copilot in Microsoft 365, a presentation by Christoforos Vlachos, Senior Solutions Manager – Modern Workplace, Uni Systems
Generating privacy-protected synthetic data using Secludy and MilvusZilliz
During this demo, the founders of Secludy will demonstrate how their system utilizes Milvus to store and manipulate embeddings for generating privacy-protected synthetic data. Their approach not only maintains the confidentiality of the original data but also enhances the utility and scalability of LLMs under privacy constraints. Attendees, including machine learning engineers, data scientists, and data managers, will witness first-hand how Secludy's integration with Milvus empowers organizations to harness the power of LLMs securely and efficiently.
Programming Foundation Models with DSPy - Meetup SlidesZilliz
Prompting language models is hard, while programming language models is easy. In this talk, I will discuss the state-of-the-art framework DSPy for programming foundation models with its powerful optimizers and runtime constraint system.
In the rapidly evolving landscape of technologies, XML continues to play a vital role in structuring, storing, and transporting data across diverse systems. The recent advancements in artificial intelligence (AI) present new methodologies for enhancing XML development workflows, introducing efficiency, automation, and intelligent capabilities. This presentation will outline the scope and perspective of utilizing AI in XML development. The potential benefits and the possible pitfalls will be highlighted, providing a balanced view of the subject.
We will explore the capabilities of AI in understanding XML markup languages and autonomously creating structured XML content. Additionally, we will examine the capacity of AI to enrich plain text with appropriate XML markup. Practical examples and methodological guidelines will be provided to elucidate how AI can be effectively prompted to interpret and generate accurate XML markup.
Further emphasis will be placed on the role of AI in developing XSLT, or schemas such as XSD and Schematron. We will address the techniques and strategies adopted to create prompts for generating code, explaining code, or refactoring the code, and the results achieved.
The discussion will extend to how AI can be used to transform XML content. In particular, the focus will be on the use of AI XPath extension functions in XSLT, Schematron, Schematron Quick Fixes, or for XML content refactoring.
The presentation aims to deliver a comprehensive overview of AI usage in XML development, providing attendees with the necessary knowledge to make informed decisions. Whether you’re at the early stages of adopting AI or considering integrating it in advanced XML development, this presentation will cover all levels of expertise.
By highlighting the potential advantages and challenges of integrating AI with XML development tools and languages, the presentation seeks to inspire thoughtful conversation around the future of XML development. We’ll not only delve into the technical aspects of AI-powered XML development but also discuss practical implications and possible future directions.
How to Get CNIC Information System with Paksim Ga.pptxdanishmna97
Pakdata Cf is a groundbreaking system designed to streamline and facilitate access to CNIC information. This innovative platform leverages advanced technology to provide users with efficient and secure access to their CNIC details.
Monitoring and Managing Anomaly Detection on OpenShift.pdfTosin Akinosho
Monitoring and Managing Anomaly Detection on OpenShift
Overview
Dive into the world of anomaly detection on edge devices with our comprehensive hands-on tutorial. This SlideShare presentation will guide you through the entire process, from data collection and model training to edge deployment and real-time monitoring. Perfect for those looking to implement robust anomaly detection systems on resource-constrained IoT/edge devices.
Key Topics Covered
1. Introduction to Anomaly Detection
- Understand the fundamentals of anomaly detection and its importance in identifying unusual behavior or failures in systems.
2. Understanding Edge (IoT)
- Learn about edge computing and IoT, and how they enable real-time data processing and decision-making at the source.
3. What is ArgoCD?
- Discover ArgoCD, a declarative, GitOps continuous delivery tool for Kubernetes, and its role in deploying applications on edge devices.
4. Deployment Using ArgoCD for Edge Devices
- Step-by-step guide on deploying anomaly detection models on edge devices using ArgoCD.
5. Introduction to Apache Kafka and S3
- Explore Apache Kafka for real-time data streaming and Amazon S3 for scalable storage solutions.
6. Viewing Kafka Messages in the Data Lake
- Learn how to view and analyze Kafka messages stored in a data lake for better insights.
7. What is Prometheus?
- Get to know Prometheus, an open-source monitoring and alerting toolkit, and its application in monitoring edge devices.
8. Monitoring Application Metrics with Prometheus
- Detailed instructions on setting up Prometheus to monitor the performance and health of your anomaly detection system.
9. What is Camel K?
- Introduction to Camel K, a lightweight integration framework built on Apache Camel, designed for Kubernetes.
10. Configuring Camel K Integrations for Data Pipelines
- Learn how to configure Camel K for seamless data pipeline integrations in your anomaly detection workflow.
11. What is a Jupyter Notebook?
- Overview of Jupyter Notebooks, an open-source web application for creating and sharing documents with live code, equations, visualizations, and narrative text.
12. Jupyter Notebooks with Code Examples
- Hands-on examples and code snippets in Jupyter Notebooks to help you implement and test anomaly detection models.
Ivanti’s Patch Tuesday breakdown goes beyond patching your applications and brings you the intelligence and guidance needed to prioritize where to focus your attention first. Catch early analysis on our Ivanti blog, then join industry expert Chris Goettl for the Patch Tuesday Webinar Event. There we’ll do a deep dive into each of the bulletins and give guidance on the risks associated with the newly-identified vulnerabilities.
In his public lecture, Christian Timmerer provides insights into the fascinating history of video streaming, starting from its humble beginnings before YouTube to the groundbreaking technologies that now dominate platforms like Netflix and ORF ON. Timmerer also presents provocative contributions of his own that have significantly influenced the industry. He concludes by looking at future challenges and invites the audience to join in a discussion.
Threats to mobile devices are more prevalent and increasing in scope and complexity. Users of mobile devices desire to take full advantage of the features
available on those devices, but many of the features provide convenience and capability but sacrifice security. This best practices guide outlines steps the users can take to better protect personal devices and information.
CAKE: Sharing Slices of Confidential Data on BlockchainClaudio Di Ciccio
Presented at the CAiSE 2024 Forum, Intelligent Information Systems, June 6th, Limassol, Cyprus.
Synopsis: Cooperative information systems typically involve various entities in a collaborative process within a distributed environment. Blockchain technology offers a mechanism for automating such processes, even when only partial trust exists among participants. The data stored on the blockchain is replicated across all nodes in the network, ensuring accessibility to all participants. While this aspect facilitates traceability, integrity, and persistence, it poses challenges for adopting public blockchains in enterprise settings due to confidentiality issues. In this paper, we present a software tool named Control Access via Key Encryption (CAKE), designed to ensure data confidentiality in scenarios involving public blockchains. After outlining its core components and functionalities, we showcase the application of CAKE in the context of a real-world cyber-security project within the logistics domain.
Paper: https://doi.org/10.1007/978-3-031-61000-4_16
Driving Business Innovation: Latest Generative AI Advancements & Success StorySafe Software
Are you ready to revolutionize how you handle data? Join us for a webinar where we’ll bring you up to speed with the latest advancements in Generative AI technology and discover how leveraging FME with tools from giants like Google Gemini, Amazon, and Microsoft OpenAI can supercharge your workflow efficiency.
During the hour, we’ll take you through:
Guest Speaker Segment with Hannah Barrington: Dive into the world of dynamic real estate marketing with Hannah, the Marketing Manager at Workspace Group. Hear firsthand how their team generates engaging descriptions for thousands of office units by integrating diverse data sources—from PDF floorplans to web pages—using FME transformers, like OpenAIVisionConnector and AnthropicVisionConnector. This use case will show you how GenAI can streamline content creation for marketing across the board.
Ollama Use Case: Learn how Scenario Specialist Dmitri Bagh has utilized Ollama within FME to input data, create custom models, and enhance security protocols. This segment will include demos to illustrate the full capabilities of FME in AI-driven processes.
Custom AI Models: Discover how to leverage FME to build personalized AI models using your data. Whether it’s populating a model with local data for added security or integrating public AI tools, find out how FME facilitates a versatile and secure approach to AI.
We’ll wrap up with a live Q&A session where you can engage with our experts on your specific use cases, and learn more about optimizing your data workflows with AI.
This webinar is ideal for professionals seeking to harness the power of AI within their data management systems while ensuring high levels of customization and security. Whether you're a novice or an expert, gain actionable insights and strategies to elevate your data processes. Join us to see how FME and AI can revolutionize how you work with data!
HCL Notes and Domino License Cost Reduction in the World of DLAUpanagenda
Webinar Recording: https://www.panagenda.com/webinars/hcl-notes-and-domino-license-cost-reduction-in-the-world-of-dlau/
The introduction of DLAU and the CCB & CCX licensing model caused quite a stir in the HCL community. As a Notes and Domino customer, you may have faced challenges with unexpected user counts and license costs. You probably have questions on how this new licensing approach works and how to benefit from it. Most importantly, you likely have budget constraints and want to save money where possible. Don’t worry, we can help with all of this!
We’ll show you how to fix common misconfigurations that cause higher-than-expected user counts, and how to identify accounts which you can deactivate to save money. There are also frequent patterns that can cause unnecessary cost, like using a person document instead of a mail-in for shared mailboxes. We’ll provide examples and solutions for those as well. And naturally we’ll explain the new licensing model.
Join HCL Ambassador Marc Thomas in this webinar with a special guest appearance from Franz Walder. It will give you the tools and know-how to stay on top of what is going on with Domino licensing. You will be able lower your cost through an optimized configuration and keep it low going forward.
These topics will be covered
- Reducing license cost by finding and fixing misconfigurations and superfluous accounts
- How do CCB and CCX licenses really work?
- Understanding the DLAU tool and how to best utilize it
- Tips for common problem areas, like team mailboxes, functional/test users, etc
- Practical examples and best practices to implement right away
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdfMalak Abu Hammad
Discover how MongoDB Atlas and vector search technology can revolutionize your application's search capabilities. This comprehensive presentation covers:
* What is Vector Search?
* Importance and benefits of vector search
* Practical use cases across various industries
* Step-by-step implementation guide
* Live demos with code snippets
* Enhancing LLM capabilities with vector search
* Best practices and optimization strategies
Perfect for developers, AI enthusiasts, and tech leaders. Learn how to leverage MongoDB Atlas to deliver highly relevant, context-aware search results, transforming your data retrieval process. Stay ahead in tech innovation and maximize the potential of your applications.
#MongoDB #VectorSearch #AI #SemanticSearch #TechInnovation #DataScience #LLM #MachineLearning #SearchTechnology
20. function curl_setopt(CurlHandle $handle, int $option, mixed $value) : bool {}
curl_setopt($handle, 10003, 'https://example.com');
PHP Error: curl_setopt(): Argument #2 ($option) is not a valid cURL option in … on line …
curl_setopt($handle, 10002, 'https://example.com');
10002 - CURLOPT_URL
curl_setopt($handle, 10004, 'https://example.com');
10002 - CURLOPT_PROXY
Why we need Enums
21. class Post {
public const POST_STATUS_DRAFT = 'draft';
public const POST_STATUS_PENDING = 'pending';
public const POST_STATUS_RETURNED = 'returned';
public const POST_STATUS_PUBLISHED = 'published';
public string $status;
public function updateStatus(string $status): void {}
}
Why we need Enums
22. class Post {
public const POST_STATUS_DRAFT = 'draft';
public const POST_STATUS_PENDING = 'pending';
public const POST_STATUS_RETURNED = 'returned';
public const POST_STATUS_PUBLISHED = 'published';
public string $status;
public function updateStatus(string $status): void {}
}
$post = new Post();
$post->updateStatus(Post::POST_STATUS_PUBLISHED);
Why we need Enums
23. class Post {
public const POST_STATUS_DRAFT = 'draft';
public const POST_STATUS_PENDING = 'pending';
public const POST_STATUS_RETURNED = 'returned';
public const POST_STATUS_PUBLISHED = 'published';
public string $status;
public function updateStatus(string $status): void {}
}
$post = new Post();
$post->updateStatus('returned');
Why we need Enums
24. class Post {
public const POST_STATUS_DRAFT = 'draft';
public const POST_STATUS_PENDING = 'pending';
public const POST_STATUS_RETURNED = 'returned';
public const POST_STATUS_PUBLISHED = 'published';
public string $status;
public function updateStatus(string $status): void {}
}
$post = new Post();
$post->updateStatus('returned');
Why we need Enums
25. class Post {
public const POST_STATUS_DRAFT = 'draft';
public const POST_STATUS_PENDING = 'pending';
public const POST_STATUS_RETURNED = 'returned';
public const POST_STATUS_PUBLISHED = 'published';
public string $status;
public function updateStatus(string $status): void {}
}
Why we need Enums
26. class Post {
public const POST_STATUS_DRAFT = 'draft';
public const POST_STATUS_PENDING = 'pending';
public const POST_STATUS_RETURNED = 'returned';
public const POST_STATUS_PUBLISHED = 'published';
public string $status;
public function updateStatus(string $status): void {
if ( $status !== static::POST_STATUS_DRAFT
&& $status !== static::POST_STATUS_PENDING
&& $status !== static::POST_STATUS_RETURNED
&& $status !== static::POST_STATUS_PUBLISHED
) {
throw new InvalidArgumentException('Invalid state');
}
}
}
Why we need Enums
29. enum PostStatuses {
case DRAFT;
case PENDING;
case RETURNED;
case PUBLISHED;
}
How Enums Can Help
30. enum PostStatuses {
case DRAFT;
case PENDING;
case RETURNED;
case PUBLISHED;
}
class Post {
public const POST_STATUS_DRAFT = 'draft';
public const POST_STATUS_PENDING = 'pending';
public const POST_STATUS_RETURNED = 'returned';
public const POST_STATUS_PUBLISHED = 'published';
public string $status;
public function updateStatus(string $status): void {
if ( $status !== static::POST_STATUS_DRAFT
&& $status !== static::POST_STATUS_PENDING
&& $status !== static::POST_STATUS_RETURNED
&& $status !== static::POST_STATUS_PUBLISHED
) {
throw new InvalidArgumentException('Invalid state');
}
}
}
$post = new Post();
$post->updateStatus(Post::POST_STATUS_PUBLISHED);
How Enums Can Help
31. enum PostStatuses {
case DRAFT;
case PENDING;
case RETURNED;
case PUBLISHED;
}
class Post {
public const POST_STATUS_DRAFT = 'draft';
public const POST_STATUS_PENDING = 'pending';
public const POST_STATUS_RETURNED = 'returned';
public const POST_STATUS_PUBLISHED = 'published';
public string $status;
public function updateStatus(string $status): void {
if ( $status !== static::POST_STATUS_DRAFT
&& $status !== static::POST_STATUS_PENDING
&& $status !== static::POST_STATUS_RETURNED
&& $status !== static::POST_STATUS_PUBLISHED
) {
throw new InvalidArgumentException('Invalid state');
}
}
}
$post = new Post();
$post->updateStatus(Post::POST_STATUS_PUBLISHED);
How Enums Can Help
32. enum PostStatuses {
case DRAFT;
case PENDING;
case RETURNED;
case PUBLISHED;
}
class Post {
public const POST_STATUS_DRAFT = 'draft';
public const POST_STATUS_PENDING = 'pending';
public const POST_STATUS_RETURNED = 'returned';
public const POST_STATUS_PUBLISHED = 'published';
public string $status;
public function updateStatus(string $status): void {
if ( $status !== static::POST_STATUS_DRAFT
&& $status !== static::POST_STATUS_PENDING
&& $status !== static::POST_STATUS_RETURNED
&& $status !== static::POST_STATUS_PUBLISHED
) {
throw new InvalidArgumentException('Invalid state');
}
}
}
$post = new Post();
$post->updateStatus(Post::POST_STATUS_PUBLISHED);
How Enums Can Help
33. enum PostStatuses {
case DRAFT;
case PENDING;
case RETURNED;
case PUBLISHED;
}
class Post {
public const POST_STATUS_DRAFT = 'draft';
public const POST_STATUS_PENDING = 'pending';
public const POST_STATUS_RETURNED = 'returned';
public const POST_STATUS_PUBLISHED = 'published';
public PostStatuses $status;
public function updateStatus(string $status): void {
if ( $status !== static::POST_STATUS_DRAFT
&& $status !== static::POST_STATUS_PENDING
&& $status !== static::POST_STATUS_RETURNED
&& $status !== static::POST_STATUS_PUBLISHED
) {
throw new InvalidArgumentException('Invalid state');
}
}
}
$post = new Post();
$post->updateStatus(Post::POST_STATUS_PUBLISHED);
How Enums Can Help
34. enum PostStatuses {
case DRAFT;
case PENDING;
case RETURNED;
case PUBLISHED;
}
class Post {
public const POST_STATUS_DRAFT = 'draft';
public const POST_STATUS_PENDING = 'pending';
public const POST_STATUS_RETURNED = 'returned';
public const POST_STATUS_PUBLISHED = 'published';
public PostStatuses $status;
public function updateStatus(PostStatuses $status): void {
if ( $status !== static::POST_STATUS_DRAFT
&& $status !== static::POST_STATUS_PENDING
&& $status !== static::POST_STATUS_RETURNED
&& $status !== static::POST_STATUS_PUBLISHED
) {
throw new InvalidArgumentException('Invalid state');
}
}
}
$post = new Post();
$post->updateStatus(Post::POST_STATUS_PUBLISHED);
How Enums Can Help
35. enum PostStatuses {
case DRAFT;
case PENDING;
case RETURNED;
case PUBLISHED;
}
class Post {
public const POST_STATUS_DRAFT = 'draft';
public const POST_STATUS_PENDING = 'pending';
public const POST_STATUS_RETURNED = 'returned';
public const POST_STATUS_PUBLISHED = 'published';
public PostStatuses $status;
public function updateStatus(PostStatuses $status): void {
if ( $status !== static::POST_STATUS_DRAFT
&& $status !== static::POST_STATUS_PENDING
&& $status !== static::POST_STATUS_RETURNED
&& $status !== static::POST_STATUS_PUBLISHED
) {
throw new InvalidArgumentException('Invalid state');
}
}
}
$post = new Post();
$post->updateStatus(Post::POST_STATUS_PUBLISHED);
How Enums Can Help
36. enum PostStatuses {
case DRAFT;
case PENDING;
case RETURNED;
case PUBLISHED;
}
class Post {
public const POST_STATUS_DRAFT = 'draft';
public const POST_STATUS_PENDING = 'pending';
public const POST_STATUS_RETURNED = 'returned';
public const POST_STATUS_PUBLISHED = 'published';
public PostStatuses $status;
public function updateStatus(PostStatuses $status): void {
if ( $status !== static::POST_STATUS_DRAFT
&& $status !== static::POST_STATUS_PENDING
&& $status !== static::POST_STATUS_RETURNED
&& $status !== static::POST_STATUS_PUBLISHED
) {
throw new InvalidArgumentException('Invalid state');
}
}
}
$post = new Post();
$post->updateStatus(Post::POST_STATUS_PUBLISHED);
How Enums Can Help
37. enum PostStatuses {
case DRAFT;
case PENDING;
case RETURNED;
case PUBLISHED;
}
class Post {
public const POST_STATUS_DRAFT = 'draft';
public const POST_STATUS_PENDING = 'pending';
public const POST_STATUS_RETURNED = 'returned';
public const POST_STATUS_PUBLISHED = 'published';
public PostStatuses $status;
public function updateStatus(PostStatuses $status): void {
if ( $status !== static::POST_STATUS_DRAFT
&& $status !== static::POST_STATUS_PENDING
&& $status !== static::POST_STATUS_RETURNED
&& $status !== static::POST_STATUS_PUBLISHED
) {
throw new InvalidArgumentException('Invalid state');
}
}
}
$post = new Post();
$post->updateStatus(PostStatuses::PUBLISHED);
How Enums Can Help
38. enum PostStatuses {
case DRAFT;
case PENDING;
case RETURNED;
case PUBLISHED;
}
class Post {
public PostStatuses $status;
public function updateStatus(PostStatuses $status): void {
}
}
$post = new Post();
$post->updateStatus(PostStatuses::PUBLISHED);
How Enums Can Help
39. enum PostStatuses {
case DRAFT;
case PENDING;
case RETURNED;
case PUBLISHED;
}
function setIsSponsored(bool $sponsored): void {
}
function isSponsored(): bool {
}
setIsSponsored(true);
setIsSponsored(false);
How Enums Can Help
41. enum PostStatuses {
case DRAFT;
case PENDING;
case RETURNED;
case PUBLISHED;
}
Unit Enums
Enums in PHP 8.1
42. enum PostStatuses implements UnitEnum {
case DRAFT;
case PENDING;
case RETURNED;
case PUBLISHED;
}
Unit Enums
Enums in PHP 8.1
43. enum PostStatuses implements UnitEnum {
case DRAFT;
case PENDING;
case RETURNED;
case PUBLISHED;
}
interface UnitEnum {
public static function cases(): array;
}
Unit Enums
Enums in PHP 8.1
44. enum PostStatuses implements UnitEnum {
case DRAFT;
case PENDING;
case RETURNED;
case PUBLISHED;
}
interface UnitEnum {
public static function cases(): array;
}
echo PostStatuses::DRAFT->name;
// "DRAFT"
Unit Enums
Enums in PHP 8.1
45. Backed Enums extend Unit Enums
enum PostStatuses: string {
case DRAFT = 'draft';
case PENDING = 'pending’;
case RETURNED = 'returned';
case PUBLISHED = 'published';
}
Backed Enums
Enums in PHP 8.1
46. enum PostStatuses: string implements BackedEnum {
case DRAFT = 'draft';
case PENDING = 'pending’;
case RETURNED = 'returned';
case PUBLISHED = 'published';
}
Backed Enums extend Unit Enums
Backed Enums
Enums in PHP 8.1
47. enum PostStatuses: string implements BackedEnum {
case DRAFT = 'draft';
case PENDING = 'pending’;
case RETURNED = 'returned';
case PUBLISHED = 'published';
}
interface BackedEnum extends UnitEnum {
public static function from(int|string $value): static;
public static function tryFrom(int|string $value): ?static;
}
Backed Enums extend Unit Enums
Backed Enums
echo PostStatuses::DRAFT->name;
// "DRAFT“
echo PostStatuses::DRAFT->value;
// "draft"
Enums in PHP 8.1
50. Enum Semantics
Enum
Enumerated type that contains a fixed number of members.
A type that is supported as parameter, return, and property type in PHP,
and the type is enforced by PHP itself.
52. Enum Semantics
Enum
Enumerated type that contains a fixed number of members.
Members of an Enum is fixed at the declaration time.
An enumerated member is identical to the same member everywhere.
Enums must not contain state.
53. Enum Semantics
Enumerated types
enum Suit {
case Spades;
case Hearts;
case Clubs;
case Diamonds;
}
function play_card(Suit $suit, string $card) {}
function pick_a_suit(): Suit {
return Suit::Spades;
}
play_card(Suit::Spades, 'A');
var_dump(pick_a_suit());
// enum(Suit::Spades)
54. Enum Semantics
enum Suit {
case Spades;
case Hearts;
case Clubs;
case Diamonds;
}
function play_card(Suit $suit, string $card) {}
function pick_a_suit(): Suit {
return Suit::Spades;
}
play_card(Fruits::Apple);
play_card(Languages::English);
play_card('potato');
Fatal error: Uncaught TypeError: play_card(): Argument #1
($suit) must be of type Suit, string given
Enumerated types
56. Enum Semantics
enum Suit {
case Spades;
case Hearts;
case Clubs;
case Diamonds;
}
Closed Set
namespace FooBar;
57. Enum Semantics
enum Suit {
case Spades;
case Hearts;
case Clubs;
case Diamonds;
}
Fixed Members
Suit::Spades === Suit::Spades
58. Enum Semantics
enum Suit {
case Spades;
case Hearts;
case Clubs;
case Diamonds;
}
Fixed Members
enum RussianSuit extends Suit {}
Parse error: syntax error, unexpected token "extends",
expecting "{"
59. Enum Semantics
enum Suit {
case Spades;
case Hearts;
case Clubs;
case Diamonds;
private string $foo;
}
Fixed Members
Fatal error: Enums may not include properties
60. Enum Semantics
Enums can have zero or more cases
enum ErrorStates {
}
enum HTTPMethods {
case GET;
case POST;
}
61. Enum Semantics
Enums may have optional values
enum Suit: string {
case Clubs = '♣';
case Diamonds = '♦';
case Hearts = '♥';
case Spades = '♠';
}
62. Enum Semantics
Backed Enums must assign values for all cases
enum HTTPMethods: string {
case GET;
case POST;
}
Fatal error: Case GET of backed enum HTTPMethods must have a value
63. Enum Semantics
Enum cases and values must be unique
Fatal error: Cannot redefine class
constant Test::FOO
enum Test {
case FOO;
case FOO;
}
enum Test: string {
case FOO = 'baz';
case BAR = 'baz';
}
Fatal error: Duplicate value in
enum Test for cases FOO and BAR
64. Enum Semantics
Class Semantics
namespace FooBar;
enum PostStatuses: string implements EntityStatues {
use TestTrait;
case DRAFT = 'draft';
case PENDING = 'pending';
case RETURNED = 'returned';
case PUBLISHED = 'published’;
public static function showOff(): void {
echo __CLASS__ . static::class;
}
}
• Supports namespaces
• Supports traits
• Supports autoloading
• Supports magic constants
• Supports instanceof
• Supports methods
66. Usage Examples
enum PostStatuses: string {
case DRAFT = 'draft';
case PENDING = 'pending’;
case RETURNED = 'returned';
case PUBLISHED = 'published';
}
67. Usage Examples
enum PostStatuses: string {
case DRAFT = 'draft';
case PENDING = 'pending’;
case RETURNED = 'returned';
case PUBLISHED = 'published';
}
class Post {
private int $id;
private string $title;
private PostStatuses $status;
public function __construct(
int $id,
string $title
) {
// ...
}
}
68. Usage Examples
enum PostStatuses: string {
case DRAFT = 'draft';
case PENDING = 'pending’;
case RETURNED = 'returned';
case PUBLISHED = 'published';
}
class Post {
private int $id;
private string $title;
private PostStatuses $status;
public function __construct(
int $id,
string $title
) {
// ...
}
}
69. Usage Examples
enum PostStatuses: string {
case DRAFT = 'draft';
case PENDING = 'pending’;
case RETURNED = 'returned';
case PUBLISHED = 'published';
}
class Post {
private int $id;
private string $title;
private PostStatuses $status;
public function __construct(
int $id,
string $title
) {
// ...
}
public function updateStatus(PostStatuses $status): void {
$this->status = $status;
}
public function getStatus(): PostStatuses {
return $this->status;
}
}
70. Usage Examples
enum PostStatuses: string {
case DRAFT = 'draft';
case PENDING = 'pending’;
case RETURNED = 'returned';
case PUBLISHED = 'published';
}
class Post {
private int $id;
private string $title;
private PostStatuses $status;
public function __construct(
int $id,
string $title
) {
// ...
}
public function updateStatus(PostStatuses $status): void {
$this->status = $status;
}
public function getStatus(): PostStatuses {
return $this->status;
}
}
$stmt = $pdo->prepare("
SELECT *
FROM posts
WHERE post_status=?");
$stmt->execute([
PostStatuses::PUBLISHED->value
]);
$post = $stmt->fetch();
71. Usage Examples
enum PostStatuses: string {
case DRAFT = 'draft';
case PENDING = 'pending’;
case RETURNED = 'returned';
case PUBLISHED = 'published';
}
class Post {
private int $id;
private string $title;
private PostStatuses $status;
public function __construct(
int $id,
string $title
) {
// ...
}
public function updateStatus(PostStatuses $status): void {
$this->status = $status;
}
public function getStatus(): PostStatuses {
return $this->status;
}
}
$stmt = $pdo->prepare("
SELECT *
FROM posts
WHERE post_status=?");
$stmt->execute([
PostStatuses::PUBLISHED->value
]);
$post = $stmt->fetch();
72. Usage Examples
enum PostStatuses: string {
case DRAFT = 'draft';
case PENDING = 'pending’;
case RETURNED = 'returned';
case PUBLISHED = 'published';
}
class Post {
private int $id;
private string $title;
private PostStatuses $status;
public function __construct(
int $id,
string $title
) {
// ...
}
public function updateStatus(PostStatuses $status): void {
$this->status = $status;
}
public function getStatus(): PostStatuses {
return $this->status;
}
}
$sql = "
INSERT INTO
posts (id, title, post_status)
VALUES
(:id, :title, :post_status)";
$stmt= $pdo->prepare($sql);
$stmt->execute([
'id' => $post->getId(),
'title' => $post->getTitle(),
'post_status' => $post->getStatus()->value,
]);
73. Usage Examples
enum PostStatuses: string {
case DRAFT = 'draft';
case PENDING = 'pending’;
case RETURNED = 'returned';
case PUBLISHED = 'published';
}
class Post {
private int $id;
private string $title;
private PostStatuses $status;
public function __construct(
int $id,
string $title
) {
// ...
}
public function updateStatus(PostStatuses $status): void {
$this->status = $status;
}
public function getStatus(): PostStatuses {
return $this->status;
}
}
$sql = "
INSERT INTO
posts (id, title, post_status)
VALUES
(:id, :title, :post_status)";
$stmt= $pdo->prepare($sql);
$stmt->execute([
'id' => $post->getId(),
'title' => $post->getTitle(),
'post_status' => $post->getStatus()->value,
]);
74. Usage Examples
enum PostStatuses: string {
case DRAFT = 'draft';
case PENDING = 'pending’;
case RETURNED = 'returned';
case PUBLISHED = 'published';
}
class Post {
private int $id;
private string $title;
private PostStatuses $status;
public function __construct(
int $id,
string $title
) {
// ...
}
public function updateStatus(PostStatuses $status): void {
$this->status = $status;
}
public function getStatus(): PostStatuses {
return $this->status;
}
}
$result = [
'id' => 42,
'title' => 'PHP Enums',
'post_status' => 'published',
];
$post = new Post(
$result['id'],
$result['title']
);
$post->updateStatus(
PostStatuses::from($result['post_status'])
);
75. Usage Examples
enum PostStatuses: string {
case DRAFT = 'draft';
case PENDING = 'pending’;
case RETURNED = 'returned';
case PUBLISHED = 'published';
}
class Post {
private int $id;
private string $title;
private PostStatuses $status;
public function __construct(
int $id,
string $title
) {
// ...
}
public function updateStatus(PostStatuses $status): void {
$this->status = $status;
}
public function getStatus(): PostStatuses {
return $this->status;
}
}
$result = [
'id' => 42,
'title' => 'PHP Enums',
'post_status' => 'published',
];
$post = new Post(
$result['id'],
$result['title']
);
$post->updateStatus(
PostStatuses::from($result['post_status'])
);
81. Backwards Compatibility
Enums is a new syntax
Enums is a new syntax introduced in PHP 8.1, and not
supported in older PHP versions.
Parse error: syntax error, unexpected identifier "PostStatuses"
82. Backwards Compatibility
User-land PHP implementations
https://github.com/myclabs/php-enum
use MyCLabsEnumEnum;
class PostStatuses extends Enum {
private const DRAFT = 'draft';
private const PENDING = 'pending';
private const RETURNED = 'returned';
private const PUBLISHED = 'published';
}