Given at Zendcon 2008 as a regular session.
An overview of new features in PHP 5.2, how to architect with the new features in mind, and why it was important to upgrade
Architecting for PHP5 - Why "Runs on PHP5" is not "Written for PHP5"ZendCon
Does your application merely run on PHP5? Do you write complicated code unaware that PHP5 has a built in solution that is twice as fast? PHP5 is an evolutionary step forward from PHP4 but everyone can find new weapons for their toolbelt and enhance their applications for speed and maintainability. Learn how to make your project "Written for PHP5" not "Runs on PHP5"
Refactoring, Agile Entwicklung, Continuous Integration – all diese für nachhaltigen Erfolg wichtigen Vorgehensweisen setzen Erfahrung mit Unit Testing voraus. Abseits von den üblichen "Bowling"-Beispielen möchten wir gerne einen Crashkurs inkl. Best Practices für das erfolgreiche Unit Testing durchführen. Anhand eines Beispielprojekts auf Basis des Zend Frameworks werden wir nach der Installation von PHPUnit auf allen Notebooks gemeinsam eine kleine Applikation aufbauen, die durchgehend Test-driven entwickelt wird.
Pluggable plugins allow developers to build reusable plugin components in a more secure and maintainable way compared to traditional monolithic plugins. They are constructed by teams using object-oriented programming principles like inheritance, which allows components to be extended while reusing common functionality. This makes the code more modular and customizable. Real-world examples show how pluggable components can be built and integrated into projects like photo galleries and ecommerce systems to solve problems like adding custom image sizes or integrating external inventory systems.
This document provides an introduction to object oriented PHP by explaining key concepts like encapsulation, inheritance, polymorphism, and abstraction. It defines classes, objects, properties, methods, and constructs. Examples are provided to demonstrate how to define classes, instantiate objects, set properties, create and extend classes, implement interfaces and abstract classes, and override methods.
The document discusses various features and capabilities of PHPUnit for testing PHP code. It covers command line options for PHPUnit like filters and coverage reports. It also covers different types of assertions for validating test expectations, using annotations to organize tests, and special tests for things like exceptions. The document aims to explain some of the more advanced but lesser known aspects of using PHPUnit for testing.
This document summarizes jQuery secrets presented by Bastian Feder. It discusses utilities like jQuery.data() and jQuery.removeData() for saving and removing state on DOM elements. It also covers AJAX settings, events, extending jQuery, and jQuery plugins. The presentation provides code examples for working with data, events, namespaces, AJAX, and extending jQuery functionality.
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 ssertions like 'assertEquals()' or
'assertTrue()' and are complaining about how hard it is to test the code even when the tests are written first. This talk is about all the stuff not used on a daily basis. It shows you some nice features of PHPUnit and how to use them for your benefit.
Architecting for PHP5 - Why "Runs on PHP5" is not "Written for PHP5"ZendCon
Does your application merely run on PHP5? Do you write complicated code unaware that PHP5 has a built in solution that is twice as fast? PHP5 is an evolutionary step forward from PHP4 but everyone can find new weapons for their toolbelt and enhance their applications for speed and maintainability. Learn how to make your project "Written for PHP5" not "Runs on PHP5"
Refactoring, Agile Entwicklung, Continuous Integration – all diese für nachhaltigen Erfolg wichtigen Vorgehensweisen setzen Erfahrung mit Unit Testing voraus. Abseits von den üblichen "Bowling"-Beispielen möchten wir gerne einen Crashkurs inkl. Best Practices für das erfolgreiche Unit Testing durchführen. Anhand eines Beispielprojekts auf Basis des Zend Frameworks werden wir nach der Installation von PHPUnit auf allen Notebooks gemeinsam eine kleine Applikation aufbauen, die durchgehend Test-driven entwickelt wird.
Pluggable plugins allow developers to build reusable plugin components in a more secure and maintainable way compared to traditional monolithic plugins. They are constructed by teams using object-oriented programming principles like inheritance, which allows components to be extended while reusing common functionality. This makes the code more modular and customizable. Real-world examples show how pluggable components can be built and integrated into projects like photo galleries and ecommerce systems to solve problems like adding custom image sizes or integrating external inventory systems.
This document provides an introduction to object oriented PHP by explaining key concepts like encapsulation, inheritance, polymorphism, and abstraction. It defines classes, objects, properties, methods, and constructs. Examples are provided to demonstrate how to define classes, instantiate objects, set properties, create and extend classes, implement interfaces and abstract classes, and override methods.
The document discusses various features and capabilities of PHPUnit for testing PHP code. It covers command line options for PHPUnit like filters and coverage reports. It also covers different types of assertions for validating test expectations, using annotations to organize tests, and special tests for things like exceptions. The document aims to explain some of the more advanced but lesser known aspects of using PHPUnit for testing.
This document summarizes jQuery secrets presented by Bastian Feder. It discusses utilities like jQuery.data() and jQuery.removeData() for saving and removing state on DOM elements. It also covers AJAX settings, events, extending jQuery, and jQuery plugins. The presentation provides code examples for working with data, events, namespaces, AJAX, and extending jQuery functionality.
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 ssertions like 'assertEquals()' or
'assertTrue()' and are complaining about how hard it is to test the code even when the tests are written first. This talk is about all the stuff not used on a daily basis. It shows you some nice features of PHPUnit and how to use them for your benefit.
The document discusses principles of writing clean code, including:
- Using consistent code style and formatting through style guides and linters.
- Avoiding duplicate code through principles like DRY.
- Using intention-revealing names for variables, functions, and classes.
- Writing small, single-purpose functions at the same level of abstraction.
- Adding guard clauses and error handling to make code logic cleaner.
- Configuring code through object properties rather than hardcoding values.
The document summarizes the state of the Lithium framework. It discusses project and community stats including contributors and issues closed. It outlines progress on the roadmap including new features like encrypting and signing cookies, nesting routes, and error handling. Upcoming features mentioned are HTTP service classes, filtering and sorting collections, and schema and multibyte classes. Community plugins are highlighted and tips and tricks are provided before opening for Q&A.
Lithium: The Framework for People Who Hate FrameworksNate Abele
This is the presentation was given at ConFoo on March 11th by Nate Abele and Joël Perras, and is an introduction to the architectural problems with other frameworks that Lithium was designed to address, and how it addresses them. It also introduces programming paradigms like functional and aspect-oriented programming which address issues that OOP doesn't account for.
Finally, the talk provides a quick overview of the innovative and unparalleled features that Lithium provides, including the data layer, which supports both relational and non-relational databases.
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.
The most hated thing a developer can imagine is writing documentation but on the other hand nothing can compare with a well documented source code if you want to change or extend some code. PhpDocumentor is one of many tools enabling you to parse the inline documentation and generate well structured and referenced documents. This tallk will show you how to get the most out of phpDocumentor and shall enable you to write fantastic documentation.
The most hated thing a developer can imageine is writing documentation but on the other hand nothing can compare with a well documented source code if you want to change or extend some code. PhpDocumentor is one of many tools enabling you to parse the inline documentation and generate well structured and referenced documents. This tallk will show you how to get the most out of phpDocumentor and shall enable you to write fantastic documentation.
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.
This document discusses the principles of "Object Calisthenics", which are nine rules of thumb for writing better object-oriented code. The rules focus on ideas like reducing indentation levels, avoiding else keywords, wrapping primitive types, keeping collections as first-class objects, limiting dots/arrows per line, avoiding abbreviations, keeping entities small, limiting instance variables per class, and avoiding getters/setters. Following these rules aims to improve code qualities like cohesion, loose coupling, readability and testability. The document provides examples of refactoring code according to these principles.
The document describes three Java programs for calculating simple mathematical operations and values:
1. A calculator program that allows users to enter two numbers and select a mathematical operation (addition, subtraction, multiplication, or division) to perform the calculation.
2. A program that calculates severance pay values based on a user's time of service and monthly salary.
3. A program that provides budget estimates for different construction/remodeling jobs based on area size and material selections.
The document summarizes Dmitry Soshnikov's presentation on ECMAScript 6 features at the HelsinkiJS meetup on December 12, 2011. Key features discussed include default function parameters, modules system, quasi-literals for string templates, array comprehensions, maps and weak maps, destructuring assignment, rest operator for function arguments, proxy objects for meta programming, and struct types.
Object Oriented Programming (OOP) allows developers to organize complex programs using classes and objects. OOP uses concepts like encapsulation, inheritance and polymorphism to keep data and functionality together in objects. The basic building blocks in OOP are classes, which define the properties and methods of an object, and objects, which are instances of classes. Classes can inherit properties and methods from parent classes, and objects can be identified and compared using operators like instanceof. Magic methods allow objects to override default behavior for operations like property access, method calling and object destruction.
Doctrine with Symfony - SymfonyCon 2019julien pauli
This document provides an overview of the Doctrine project, including its ORM and DBAL components. It discusses the architecture of Doctrine, including entities, the entity manager, unit of work, repositories, and metadata. It explains how Doctrine maps objects to the database using its ORM. Key concepts covered include the entity manager methods like find(), persist(), and flush(), managing entity state and changes. The document also discusses Doctrine's DBAL for database abstraction and query building.
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.
The document discusses the Apache Commons project, which develops reusable Java components. It notes that Commons components allow for faster and smaller development by avoiding reinventing common functions. The document outlines several active Commons components like Collections, IO, Lang, and Logging, as well as sandbox and dormant components. It emphasizes that 80% of Commons components have no dependencies on each other, promoting flexibility and reuse.
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.
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.
Traits in PHP allow for code reuse and multiple inheritance by defining reusable sets of methods that can be used in multiple classes. The document discusses using traits to define a permissions trait that implements magic methods like __call to control access to methods based on permissions. It provides an example of how to define a feature access control list, apply the permissions trait to a secured class, and throw exceptions when unauthorized methods are called. This allows restricting code execution to authorized users and tracking all method calls for security and analytics purposes.
Der Vortrag "Zend Framework meets Doctrine 2" von Paul Seiffert erklärt die Verwendung von Doctrine 2 in Projekten, die auf Zend Framework (ZF) basieren. Zuerst wird Paul dabei auf das Doctrine 2 ORM und dessen
grundsätzliche Verwendung eingehen (es wird also kein Doctrine 2 - Wissen vorausgesetzt), im weiteren Verlauf wird er die Einbindung des ORMs in ZF-Projekte erklären. Zum Schluss zeigt Paul ein kleines Beispiel-Projekt, in dem ZF und Doctrine 2 gemeinsam zum Einsatz kommen.
The document discusses principles of writing clean code, including:
- Using consistent code style and formatting through style guides and linters.
- Avoiding duplicate code through principles like DRY.
- Using intention-revealing names for variables, functions, and classes.
- Writing small, single-purpose functions at the same level of abstraction.
- Adding guard clauses and error handling to make code logic cleaner.
- Configuring code through object properties rather than hardcoding values.
The document summarizes the state of the Lithium framework. It discusses project and community stats including contributors and issues closed. It outlines progress on the roadmap including new features like encrypting and signing cookies, nesting routes, and error handling. Upcoming features mentioned are HTTP service classes, filtering and sorting collections, and schema and multibyte classes. Community plugins are highlighted and tips and tricks are provided before opening for Q&A.
Lithium: The Framework for People Who Hate FrameworksNate Abele
This is the presentation was given at ConFoo on March 11th by Nate Abele and Joël Perras, and is an introduction to the architectural problems with other frameworks that Lithium was designed to address, and how it addresses them. It also introduces programming paradigms like functional and aspect-oriented programming which address issues that OOP doesn't account for.
Finally, the talk provides a quick overview of the innovative and unparalleled features that Lithium provides, including the data layer, which supports both relational and non-relational databases.
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.
The most hated thing a developer can imagine is writing documentation but on the other hand nothing can compare with a well documented source code if you want to change or extend some code. PhpDocumentor is one of many tools enabling you to parse the inline documentation and generate well structured and referenced documents. This tallk will show you how to get the most out of phpDocumentor and shall enable you to write fantastic documentation.
The most hated thing a developer can imageine is writing documentation but on the other hand nothing can compare with a well documented source code if you want to change or extend some code. PhpDocumentor is one of many tools enabling you to parse the inline documentation and generate well structured and referenced documents. This tallk will show you how to get the most out of phpDocumentor and shall enable you to write fantastic documentation.
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.
This document discusses the principles of "Object Calisthenics", which are nine rules of thumb for writing better object-oriented code. The rules focus on ideas like reducing indentation levels, avoiding else keywords, wrapping primitive types, keeping collections as first-class objects, limiting dots/arrows per line, avoiding abbreviations, keeping entities small, limiting instance variables per class, and avoiding getters/setters. Following these rules aims to improve code qualities like cohesion, loose coupling, readability and testability. The document provides examples of refactoring code according to these principles.
The document describes three Java programs for calculating simple mathematical operations and values:
1. A calculator program that allows users to enter two numbers and select a mathematical operation (addition, subtraction, multiplication, or division) to perform the calculation.
2. A program that calculates severance pay values based on a user's time of service and monthly salary.
3. A program that provides budget estimates for different construction/remodeling jobs based on area size and material selections.
The document summarizes Dmitry Soshnikov's presentation on ECMAScript 6 features at the HelsinkiJS meetup on December 12, 2011. Key features discussed include default function parameters, modules system, quasi-literals for string templates, array comprehensions, maps and weak maps, destructuring assignment, rest operator for function arguments, proxy objects for meta programming, and struct types.
Object Oriented Programming (OOP) allows developers to organize complex programs using classes and objects. OOP uses concepts like encapsulation, inheritance and polymorphism to keep data and functionality together in objects. The basic building blocks in OOP are classes, which define the properties and methods of an object, and objects, which are instances of classes. Classes can inherit properties and methods from parent classes, and objects can be identified and compared using operators like instanceof. Magic methods allow objects to override default behavior for operations like property access, method calling and object destruction.
Doctrine with Symfony - SymfonyCon 2019julien pauli
This document provides an overview of the Doctrine project, including its ORM and DBAL components. It discusses the architecture of Doctrine, including entities, the entity manager, unit of work, repositories, and metadata. It explains how Doctrine maps objects to the database using its ORM. Key concepts covered include the entity manager methods like find(), persist(), and flush(), managing entity state and changes. The document also discusses Doctrine's DBAL for database abstraction and query building.
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.
The document discusses the Apache Commons project, which develops reusable Java components. It notes that Commons components allow for faster and smaller development by avoiding reinventing common functions. The document outlines several active Commons components like Collections, IO, Lang, and Logging, as well as sandbox and dormant components. It emphasizes that 80% of Commons components have no dependencies on each other, promoting flexibility and reuse.
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.
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.
Traits in PHP allow for code reuse and multiple inheritance by defining reusable sets of methods that can be used in multiple classes. The document discusses using traits to define a permissions trait that implements magic methods like __call to control access to methods based on permissions. It provides an example of how to define a feature access control list, apply the permissions trait to a secured class, and throw exceptions when unauthorized methods are called. This allows restricting code execution to authorized users and tracking all method calls for security and analytics purposes.
Der Vortrag "Zend Framework meets Doctrine 2" von Paul Seiffert erklärt die Verwendung von Doctrine 2 in Projekten, die auf Zend Framework (ZF) basieren. Zuerst wird Paul dabei auf das Doctrine 2 ORM und dessen
grundsätzliche Verwendung eingehen (es wird also kein Doctrine 2 - Wissen vorausgesetzt), im weiteren Verlauf wird er die Einbindung des ORMs in ZF-Projekte erklären. Zum Schluss zeigt Paul ein kleines Beispiel-Projekt, in dem ZF und Doctrine 2 gemeinsam zum Einsatz kommen.
Writing and using php streams and sockets tek11Elizabeth Smith
Streams provide a generic way to access input and output in PHP and were originally introduced in the 1950s as a standard way to handle input/output. PHP implements streams using wrappers that tell streams how to handle specific protocols and encodings, and filters that can transform stream data. Common stream wrappers in PHP include file, http, ftp, and php streams for interacting with system inputs and outputs.
This document provides a summary of the Standard PHP Library (SPL) which is a collection of classes and interfaces that provide solutions to common problems. It discusses key SPL components like arrays, iterators, exceptions, maps, sets, heaps, queues and stacks. The SPL aims to standardize data access and provides interfaces for traversing data structures, working with files and implementing patterns like Observer.
1. Unicode is an international standard for representing characters across different languages. It allows websites and software to support multiple languages.
2. When working with Unicode in PHP, it is important to use UTF-8 encoding, and extensions like intl provide helpful internationalization functions.
3. Common issues include character encoding problems between databases, files and PHP strings, so ensuring consistent encoding is crucial.
This document provides steps to improve oneself which include listing your strengths and weaknesses, setting personal goals, meeting new people by speed dating, learning from and teaching others, and ultimately winning by becoming the solution.
From Tek-X Cross Platform interoperability with PHP including history lesson, a bit about each category of operating systems, and gotchas related to PHP
This document discusses object-oriented programming (OOP) concepts in PHP, including classes, objects, methods, properties, scope, inheritance, static methods/properties, constants, abstraction, and interfaces. It provides examples of declaring classes and objects, using constructors and destructors, defining public/private/protected methods and properties, inheritance, overriding methods, accessing parent classes, static keywords, class constants, abstract classes, and interfaces. The key concepts of OOP such as encapsulation, polymorphism and inheritance are demonstrated through PHP code examples.
PHP is an object-oriented programming language that supports fundamental object-oriented programming features like encapsulation, inheritance, and polymorphism. Key concepts covered in the document include:
- Classes allow data and functions to be grouped together, and instances of classes are called objects.
- Access specifiers like public, private, and protected determine visibility of class members. Private members can only be accessed within the class, while public members can be accessed anywhere.
- Constructors are special methods that initialize an object when it is created. Destructors are called when objects are destroyed.
- Inheritance allows new classes to inherit attributes and behaviors from existing classes. Polymorphism allows different classes to have similarly
The document discusses object-oriented programming in PHP. It covers basic class definitions, constructors and destructors, visibility of properties and methods, inheritance, the scope resolution operator, abstract classes, and interfaces. Some key points include:
- Classes define properties and methods within curly braces, and objects are instantiated with the new keyword.
- Constructors and destructors are special methods that get called when an object is created or destroyed.
- Visibility of properties and methods can be public, protected, or private to control access.
- Inheritance allows a child class to extend a parent class and inherit its properties and methods.
- Abstract classes define abstract methods that must be implemented in child classes.
Demystifying Object-Oriented Programming - Lone Star PHPAlena Holligan
Abstraction, Encapsulation, Polymorphism, and Interfaces: whether you’ve been programming in PHP for years or are just starting your journey, these terms can be overwhelming even on a good day. Variables, conditionals, those all make sense. But this whole Object-Oriented thing is WAY more complicated. Not only that, people that already understand it act like it’s so easy and they talk right over the simple questions and never explain the basic concepts in a way that actually makes sense. In this session we’ll take you through real life examples of Object-Oriented terminology in a way that will make sense of all the mumbo jumbo and allow you to utilizing OOP immediately.
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.
This document provides an overview of object-oriented programming concepts in PHP including static methods and properties, constants, abstraction and interfaces, overloading, object iteration, cloning, serialization, namespaces, and autoloading classes. Key points covered include how to define static class members, constants, abstract classes and interfaces, magic methods for overloading, implementing interfaces for object iteration, cloning objects and the clone constructor, serializing and unserializing objects, using namespaces to organize code, and defining an autoload function to include class files automatically.
international PHP2011_Bastian Feder_The most unknown Parts of PHPUnitsmueller_sandsmedia
PHPUnit provides many features beyond just testing code including:
- Command line options like --testdox to generate styled reports and --filter to select specific tests.
- Annotations like @covers and @group to document and organize tests.
- Various assertion methods like assertContains(), assertType(), and assertSelectRegExp() to validate test conditions.
- Test listeners that get called at different test execution stages to add functionality.
- Ways to test exceptions like @expectedException and try/catch blocks.
- Mocking features to isolate tests from external dependencies using callbacks and return values.
- The document discusses object-oriented programming concepts in PHP including classes, objects, encapsulation, inheritance, and polymorphism.
- It provides examples of defining classes with properties and methods, and using access specifiers like public, private, and protected.
- Constructors and destructors are explained, as well as how to instantiate objects and use objects in arrays or pass them as references to functions.
This document provides an overview of object-oriented programming (OOP) concepts in PHP. It discusses key OOP features like classes, objects, inheritance, encapsulation, abstraction, and interfaces. It explains why OOP is useful for modularity, abstraction, information hiding, structured design, hierarchy, and continuity. Main language features in PHP like classes, inheritance, visibility, abstraction, interfaces, and polymorphism are also covered. Real-world examples of classes, objects, inheritance and interfaces in PHP code are provided.
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.
Alena Holligan presented on demystifying object-oriented programming in PHP. She discussed key OOP concepts like classes, objects, inheritance, polymorphism, interfaces, abstract classes and traits. The presentation covered terminology, creating classes and objects, encapsulation, inheritance and polymorphism through subclasses and interfaces. Later sections discussed namespaces, type declarations, magic methods, magic constants and static methods. The goal was to explain core OOP concepts in PHP through examples and challenges for attendees.
This document provides an introduction to object-oriented programming (OOP) concepts in PHP, including classes, objects, inheritance, and more. It explains that classes define the structure and behavior of objects, and objects are instances of classes. It demonstrates class and object syntax in PHP using a shape class example. It also covers inheritance, abstract classes, interfaces, visibility, static methods/properties, and determining an object's class. The document provides examples to illustrate each OOP concept discussed.
Architecture logicielle #3 : object oriented designJean Michel
The document discusses object-oriented programming concepts including objects, classes, instances, attributes, methods, interfaces, inheritance, and SOLID principles.
It begins by defining objects, classes, and instances in OOP. It provides PHP code examples to demonstrate classes, instantiating objects, and using methods and attributes. It then covers interfaces, inheritance, and polymorphism with additional PHP examples.
Finally, it discusses best practices for OOP with SOLID principles - the single responsibility, open/closed, Liskov substitution, interface segregation and dependency inversion principles. For each principle it provides an example of poor design, explains the principle, and shows how to improve the design to follow that principle.
This document provides an overview of object-oriented programming (OOP) concepts in PHP, including classes, objects, properties, methods, inheritance, abstraction, interfaces, and more. It explains the basic structure of a PHP class, how to instantiate objects, define public/private/protected visibility, use constructors, static properties and methods, inheritance between classes, abstract classes and interfaces, traits, namespaces, and various magic methods like __construct, __get, __set, etc. The document serves as a primer to OOP principles and features in PHP.
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.
The document discusses dependency injection and describes how to build a simple dependency injection container in PHP. It explains how to use anonymous functions to describe how to create objects without instantiating them. The container stores these functions and uses them to instantiate objects on demand, injecting their dependencies. This allows decoupling objects and making configuration and customization natural. The container manages both parameters and object instantiation, handles scopes like shared instances, and can be configured flexibly.
Abstraction, Encapsulation, Polymorphism, and Interfaces: whether you've been programming in PHP for years or are just starting your journey, these terms can be overwhelming even on a good day. Variables, conditionals, those all make sense. But this whole Object-Oriented thing is WAY more complicated. Not only that, people that already understand it act like it's so easy and they talk right over the simple questions and never explain the basic concepts in a way that actually makes sense. In this session we'll take you through real life examples of Object-Oriented terminology in a way that will make sense of all the mumbo jumbo and allow you to utilizing OOP immediately.
Semelhante a Runs On Php5 is not Written for PHP5 (20)
The document provides an overview of the history and workings of the internet. It describes how ARPA funded research in the 1960s to develop a decentralized network that could withstand attacks, leading to the creation of ARPANET. Key developments included packet switching, TCP/IP, DNS, personal computers, hypertext, browsers, and HTML, which together formed the foundation of today's worldwide internet. The internet allows data to be broken into packets and routed independently to a destination, ensuring reliable transmission of information.
This document discusses various computing concepts related to resources, data storage, and performance. It covers topics like hard disk drives, solid state drives, areal storage density, streams, filters, memory management, CPU performance, networking, and best practices for handling large amounts of data and potential failures. The key ideas are to use appropriate data structures, iterate/process data lazily, offload work to queues when possible, and design systems with failure in mind.
This document discusses modern SQL features beyond the SQL-92 standard, including OLAP features like grouping sets, cube, and rollup for multi-dimensional analysis; common table expressions (WITH queries) for organizing complex queries and enabling recursion; lateral joins for iterating over query results; window functions for ranking and aggregating over partitions; and the use of JSON data types in PostgreSQL for combining SQL and NoSQL capabilities. It provides examples and discusses support for these features across major database systems.
This document provides an overview of PHP extensions, including reasons for creating extensions, the extension development process, and advanced extension topics. Some key points:
- Extensions allow PHP to interface with C/C++ libraries, modify how the PHP engine works, and increase performance of slow code.
- The extension development process includes setting up the compile environment, writing the module definition, adding functions, and testing.
- Advanced topics include using global variables, custom object handling, memory management, and threading safety. Well-documented extensions can be proposed for inclusion in the PECL repository.
This document discusses various computing concepts related to resources and performance in PHP applications. It covers topics like data storage technologies, areal storage density of hard drives and solid state drives, streams as a way to access input and output generically in PHP, using filters to perform operations on stream data, common issues like running out of memory and how to address them through better programming practices, limitations of CPU and how to distribute load through job queuing, and basics of networking like IP addresses, TCP, and using sockets. The key advice is to assume large amounts of data and potential failures, use appropriate data storage, avoid unnecessary processing in memory, optimize code through profiling, and offload work to other systems when possible.
The document discusses various concepts related to programming and physics, including:
- There are physical limits to what hardware can do based on laws of physics.
- Arrays can be inefficient for storing large amounts of data and other methods may be better.
- Streams provide a standard way to access input and output in a linear, chunk-based fashion and are widely used across programming languages and systems.
This document provides an overview of PHP extensions, including reasons for creating extensions, the extension development process, and advanced extension topics. It begins with an introduction to extensions and why developers create them. It then covers the basic process of creating an extension, including setting up the development environment, writing the scaffolding, and compiling and testing the extension. Later sections discuss more advanced extension features like classes, methods, and object handling. The document aims to equip developers with the knowledge to begin developing their own PHP extensions and integrating PHP with external libraries.
PHP extensions allow modifying and extending the PHP language. There are different types of extensions including wrapper extensions for interfacing with C libraries, speed and algorithm extensions for optimizing slow code, and Zend extensions for modifying the PHP engine. Writing extensions requires knowledge of C, the PHP internals including zvals and the PHP lifecycle, and using tools like phpize to generate the extension scaffolding. The document provides guidance on setting up a development environment, writing extension code, and testing extensions. It also outlines best practices for extension coding.
This document discusses the inner workings of PHP including its architecture, core components like the lexer, parser, compiler and virtual machine. It covers key concepts like opcodes, variables as unions of C data types, and memory management. Understanding PHP internals like its stack and heap implementation, copy-on-write variables, and reference counting is important for optimizing performance and avoiding memory leaks. Resources and objects also have important internal representations that developers should be aware of.
Lexing and parsing involves breaking down input like code, markup languages, or configuration files into individual tokens and analyzing the syntax and structure according to formal grammars. Common techniques include using lexer generators to tokenize input and parser generators to construct parse trees and abstract syntax trees based on formal grammars. While regular expressions are sometimes useful, lexers and parsers are better suited for many formal language tasks and ensure well-formed syntax.
The document summarizes HHVM, a virtual machine for executing PHP code. Some key points:
- HHVM is a drop-in replacement for PHP that compiles PHP to bytecode and uses a just-in-time (JIT) compiler to optimize for performance.
- It supports most PHP syntax and features like Hack which adds type hints. It also has its own features like async functions, user attributes, and XHP for building components with XHTML syntax.
- HHVM is faster than PHP due to its JIT compiler which performs type inference and compiles hot code paths to native machine code. Benchmark tests show significant performance improvements over PHP for applications like Magento and Symfony.
The document discusses security as an ongoing process rather than a feature or checklist. It emphasizes that security requires thinking like a paranoid person and acknowledging that systems will eventually be hacked. The document provides steps to take such as knowing your data, users, and laws; making good security decisions; documenting everything; and practicing security processes. It also gives best practices for different security layers like input validation, authentication, authorization, and more. The overall message is that security requires constant attention and effort from all parties.
How to train the next generation of Masters One of the best ways to move yourself forward as a developer is to have mentors who can help improve your skills, or to be a mentor for a newer developer. Mentoring isn’t limited to just ‘hard’ or technical skills, and a mentoring relationships can help in all aspects of any career – be it open source, a day job, or something else entirely. Learn some skills and tips from people who make mentoring an important aspect of their lives. From how to choose a mentor and what you should expect from a relationship as a padawan, to how to deal with the trials and successes of the person you are mentoring as they grow in their career. Also learn about setting up mentorship organizations, from the kind inside a company to one purely for the good of a community.
1. The document discusses internationalization and Unicode support in PHP, covering topics like encodings, locales, formatting numbers and dates for different languages, and database and browser considerations.
2. It provides an overview of PHP extensions and functions for internationalization, including Intl, mbstring, and Iconv, and discusses their strengths and limitations.
3. Examples of internationalization practices in popular PHP frameworks and applications are examined, highlighting both best practices and common pitfalls.
This document discusses socket programming in PHP. It begins with an overview of inter-process communication and network sockets. It then covers PHP streams and how they provide a generic interface for input and output. The document dives into details of socket programming in PHP using different extensions, covering topics like creating, binding, listening for, accepting, reading and writing sockets. It also discusses blocking, selecting sockets and websockets.
The document discusses the mentor-apprentice relationship in different stages from beginning to advanced, outlining expectations, goals, and needs at each stage. It provides guidance on finding mentors and apprentices, deciding on goals, communicating, and handling issues that could arise. The overall message is that mentorship is an ongoing learning process that benefits both parties when entered into with trust, respect, and a commitment to growth.
This document provides an overview of the Standard PHP Library (SPL) including common data structures, interfaces, exceptions and iterators. It discusses how SPL components like SplAutoload, SplFileInfo and various iterators are used in popular open source projects. The document encourages developers to get involved in improving SPL through code contributions and articles and provides contact information for the presenter.
This document discusses mentoring relationships and provides advice for mentors and mentees at different stages. It notes that mentoring involves turning a person's raw potential into something useful by providing information, role modeling, advice, networking, and interaction. For mentees, the key aspects are finding a good mentor, defining goals, communicating, and having an exit strategy. Mentors should trust, listen, help mentees achieve goals, and provide constructive feedback and support. The roles and needs change as mentees progress from beginning to intermediate to advanced levels. Mentors should continue challenging mentees and helping them grow outside their comfort zones.
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?Speck&Tech
ABSTRACT: A prima vista, un mattoncino Lego e la backdoor XZ potrebbero avere in comune il fatto di essere entrambi blocchi di costruzione, o dipendenze di progetti creativi e software. La realtà è che un mattoncino Lego e il caso della backdoor XZ hanno molto di più di tutto ciò in comune.
Partecipate alla presentazione per immergervi in una storia di interoperabilità, standard e formati aperti, per poi discutere del ruolo importante che i contributori hanno in una comunità open source sostenibile.
BIO: Sostenitrice del software libero e dei formati standard e aperti. È stata un membro attivo dei progetti Fedora e openSUSE e ha co-fondato l'Associazione LibreItalia dove è stata coinvolta in diversi eventi, migrazioni e formazione relativi a LibreOffice. In precedenza ha lavorato a migrazioni e corsi di formazione su LibreOffice per diverse amministrazioni pubbliche e privati. Da gennaio 2020 lavora in SUSE come Software Release Engineer per Uyuni e SUSE Manager e quando non segue la sua passione per i computer e per Geeko coltiva la sua curiosità per l'astronomia (da cui deriva il suo nickname deneb_alpha).
For the full video of this presentation, please visit: https://www.edge-ai-vision.com/2024/06/building-and-scaling-ai-applications-with-the-nx-ai-manager-a-presentation-from-network-optix/
Robin van Emden, Senior Director of Data Science at Network Optix, presents the “Building and Scaling AI Applications with the Nx AI Manager,” tutorial at the May 2024 Embedded Vision Summit.
In this presentation, van Emden covers the basics of scaling edge AI solutions using the Nx tool kit. He emphasizes the process of developing AI models and deploying them globally. He also showcases the conversion of AI models and the creation of effective edge AI pipelines, with a focus on pre-processing, model conversion, selecting the appropriate inference engine for the target hardware and post-processing.
van Emden shows how Nx can simplify the developer’s life and facilitate a rapid transition from concept to production-ready applications.He provides valuable insights into developing scalable and efficient edge AI solutions, with a strong focus on practical implementation.
Have you ever been confused by the myriad of choices offered by AWS for hosting a website or an API?
Lambda, Elastic Beanstalk, Lightsail, Amplify, S3 (and more!) can each host websites + APIs. But which one should we choose?
Which one is cheapest? Which one is fastest? Which one will scale to meet our needs?
Join me in this session as we dive into each AWS hosting service to determine which one is best for your scenario and explain why!
Digital Marketing Trends in 2024 | Guide for Staying AheadWask
https://www.wask.co/ebooks/digital-marketing-trends-in-2024
Feeling lost in the digital marketing whirlwind of 2024? Technology is changing, consumer habits are evolving, and staying ahead of the curve feels like a never-ending pursuit. This e-book is your compass. Dive into actionable insights to handle the complexities of modern marketing. From hyper-personalization to the power of user-generated content, learn how to build long-term relationships with your audience and unlock the secrets to success in the ever-shifting digital landscape.
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.
UiPath Test Automation using UiPath Test Suite series, part 6DianaGray10
Welcome to UiPath Test Automation using UiPath Test Suite series part 6. In this session, we will cover Test Automation with generative AI and Open AI.
UiPath Test Automation with generative AI and Open AI webinar offers an in-depth exploration of leveraging cutting-edge technologies for test automation within the UiPath platform. Attendees will delve into the integration of generative AI, a test automation solution, with Open AI advanced natural language processing capabilities.
Throughout the session, participants will discover how this synergy empowers testers to automate repetitive tasks, enhance testing accuracy, and expedite the software testing life cycle. Topics covered include the seamless integration process, practical use cases, and the benefits of harnessing AI-driven automation for UiPath testing initiatives. By attending this webinar, testers, and automation professionals can gain valuable insights into harnessing the power of AI to optimize their test automation workflows within the UiPath ecosystem, ultimately driving efficiency and quality in software development processes.
What will you get from this session?
1. Insights into integrating generative AI.
2. Understanding how this integration enhances test automation within the UiPath platform
3. Practical demonstrations
4. Exploration of real-world use cases illustrating the benefits of AI-driven test automation for UiPath
Topics covered:
What is generative AI
Test Automation with generative AI and Open AI.
UiPath integration with generative AI
Speaker:
Deepak Rai, Automation Practice Lead, Boundaryless Group and UiPath MVP
AI 101: An Introduction to the Basics and Impact of Artificial IntelligenceIndexBug
Imagine a world where machines not only perform tasks but also learn, adapt, and make decisions. This is the promise of Artificial Intelligence (AI), a technology that's not just enhancing our lives but revolutionizing entire industries.
Skybuffer SAM4U tool for SAP license adoptionTatiana Kojar
Manage and optimize your license adoption and consumption with SAM4U, an SAP free customer software asset management tool.
SAM4U, an SAP complimentary software asset management tool for customers, delivers a detailed and well-structured overview of license inventory and usage with a user-friendly interface. We offer a hosted, cost-effective, and performance-optimized SAM4U setup in the Skybuffer Cloud environment. You retain ownership of the system and data, while we manage the ABAP 7.58 infrastructure, ensuring fixed Total Cost of Ownership (TCO) and exceptional services through the SAP Fiori interface.
Webinar: Designing a schema for a Data WarehouseFederico Razzoli
Are you new to data warehouses (DWH)? Do you need to check whether your data warehouse follows the best practices for a good design? In both cases, this webinar is for you.
A data warehouse is a central relational database that contains all measurements about a business or an organisation. This data comes from a variety of heterogeneous data sources, which includes databases of any type that back the applications used by the company, data files exported by some applications, or APIs provided by internal or external services.
But designing a data warehouse correctly is a hard task, which requires gathering information about the business processes that need to be analysed in the first place. These processes must be translated into so-called star schemas, which means, denormalised databases where each table represents a dimension or facts.
We will discuss these topics:
- How to gather information about a business;
- Understanding dictionaries and how to identify business entities;
- Dimensions and facts;
- Setting a table granularity;
- Types of facts;
- Types of dimensions;
- Snowflakes and how to avoid them;
- Expanding existing dimensions and facts.
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAUpanagenda
Webinar Recording: https://www.panagenda.com/webinars/hcl-notes-und-domino-lizenzkostenreduzierung-in-der-welt-von-dlau/
DLAU und die Lizenzen nach dem CCB- und CCX-Modell sind für viele in der HCL-Community seit letztem Jahr ein heißes Thema. Als Notes- oder Domino-Kunde haben Sie vielleicht mit unerwartet hohen Benutzerzahlen und Lizenzgebühren zu kämpfen. Sie fragen sich vielleicht, wie diese neue Art der Lizenzierung funktioniert und welchen Nutzen sie Ihnen bringt. Vor allem wollen Sie sicherlich Ihr Budget einhalten und Kosten sparen, wo immer möglich. Das verstehen wir und wir möchten Ihnen dabei helfen!
Wir erklären Ihnen, wie Sie häufige Konfigurationsprobleme lösen können, die dazu führen können, dass mehr Benutzer gezählt werden als nötig, und wie Sie überflüssige oder ungenutzte Konten identifizieren und entfernen können, um Geld zu sparen. Es gibt auch einige Ansätze, die zu unnötigen Ausgaben führen können, z. B. wenn ein Personendokument anstelle eines Mail-Ins für geteilte Mailboxen verwendet wird. Wir zeigen Ihnen solche Fälle und deren Lösungen. Und natürlich erklären wir Ihnen das neue Lizenzmodell.
Nehmen Sie an diesem Webinar teil, bei dem HCL-Ambassador Marc Thomas und Gastredner Franz Walder Ihnen diese neue Welt näherbringen. Es vermittelt Ihnen die Tools und das Know-how, um den Überblick zu bewahren. Sie werden in der Lage sein, Ihre Kosten durch eine optimierte Domino-Konfiguration zu reduzieren und auch in Zukunft gering zu halten.
Diese Themen werden behandelt
- Reduzierung der Lizenzkosten durch Auffinden und Beheben von Fehlkonfigurationen und überflüssigen Konten
- Wie funktionieren CCB- und CCX-Lizenzen wirklich?
- Verstehen des DLAU-Tools und wie man es am besten nutzt
- Tipps für häufige Problembereiche, wie z. B. Team-Postfächer, Funktions-/Testbenutzer usw.
- Praxisbeispiele und Best Practices zum sofortigen Umsetzen
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.
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.
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.
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdfChart Kalyan
A Mix Chart displays historical data of numbers in a graphical or tabular form. The Kalyan Rajdhani Mix Chart specifically shows the results of a sequence of numbers over different periods.
Best 20 SEO Techniques To Improve Website Visibility In SERPPixlogix Infotech
Boost your website's visibility with proven SEO techniques! Our latest blog dives into essential strategies to enhance your online presence, increase traffic, and rank higher on search engines. From keyword optimization to quality content creation, learn how to make your site stand out in the crowded digital landscape. Discover actionable tips and expert insights to elevate your SEO game.
WeTestAthens: Postman's AI & Automation Techniques
Runs On Php5 is not Written for PHP5
1. Also known as
“Elizabeth Ranting about a Pet Peeve”
Zendcon 2008 – Santa Clara, CA
2. Elizabeth Marie Smith aka auroraeosrose
Pink is good
I hate computers
I love programming
Windows will not kill you
Work at OmniTI (http://omniti.com)
Contributor on various open source projects
(including PHP, PECL and PHP-GTK)
3. Why are you here?
What are you hoping to learn?
How to improve your code for use on PHP5?
Improve meaning faster, more stable, easier to maintain
What do I want to teach?
What is available in PHP5 to help with the “improve”
What do you already know?
This is about what you CAN do not what you CAN’T do
8. Every constructor is named __construct, use
parent::__construct to chain
Careful with __destruct, headers are sent
and you can’t throw exceptions
<?php Kill da wabbit
class foo { bar Object()
protected $animal;
public function __construct($animal) { Fatal error: Call to private
$this->animal = $animal;
} bar::__construct() from invalid
context in test.php on line 34
public function __destruct() {
echo 'Kill da ' . $this->animal . PHP_EOL;
}
}
class bar {
static $singleton;
private function __construct() {}
static public function getInstance() {
if (!self::$singleton) {
self::$singleton = new self;
}
return self::$singleton;
}
}
$class = new foo('wabbit');
// $class = null; also works
unset($class);
$foo = bar::getInstance();
print_r($foo);
$foo = new bar;
9. Keep people from messing with your stuff
<?php class Bar
/** {
* Define MyClass public function test() {
*/ $this->testPrivate();
<?php class MyClass $this->testPublic();
/** { }
* Define MyClass
*/ // Declare a public constructor
class MyClass public function __construct() { } public function testPublic() {
{ echo "Bar::testPublicn";
// Declare a public method }
public $public = 'Public'; public function MyPublic() { }
protected $protected = 'Protected'; private function testPrivate() {
private $private = 'Private'; // Declare a protected method echo "Bar::testPrivaten";
protected function MyProtected() { } }
function printHello() }
{
echo $this->public; // Declare a private method
echo $this->protected; private function MyPrivate() { } class Foo extends Bar
echo $this->private; {
} // This is public public function testPublic() {
} function Foo() echo "Foo::testPublicn";
{ }
$obj = new MyClass(); $this->MyPublic();
echo $obj->public; // Works $this->MyProtected(); private function testPrivate() {
echo $obj->protected; // Fatal Error $this->MyPrivate(); echo "Foo::testPrivaten";
} }
echo $obj->private; // Fatal Error } }
$obj->printHello(); // Shows Public, Protected and Private
$myclass = new MyClass; $myFoo = new foo();
/** $myclass->MyPublic(); // Works $myFoo->test(); // Bar::testPrivate
* Define MyClass2 $myclass->MyProtected(); // Fatal Error // Foo::testPublic
*/ $myclass->MyPrivate(); // Fatal Error
class MyClass2 extends MyClass $myclass->Foo(); // Public, Protected and Private work
{
// We can redeclare the public and protected method, but not private /**
protected $protected = 'Protected2'; * Define MyClass2
*/
function printHello() class MyClass2 extends MyClass
{
echo $this->public; {
echo $this->protected; // This is public
echo $this->private; function Foo2()
} {
} $this->MyPublic();
$this->MyProtected();
$obj2 = new MyClass2(); $this->MyPrivate(); // Fatal Error
echo $obj2->public; // Works }
}
echo $obj2->private; // Undefined
echo $obj2->protected; // Fatal Error $myclass2 = new MyClass2;
$obj2->printHello(); // Shows Public, Protected2, Undefined $myclass2->MyPublic(); // Works
$myclass2-
>Foo2(); // Public and Protected work, not Private
10. In PHP4 any assignment was a clone
In PHP5 objects are passed by reference, to
copy it we have clone it
<?php 7
class foo { 7
public $bar; 9
}
2
class funky {
public $bar;
public function __clone() {
$this->bar++;
}
}
$foo = new foo();
$foo->bar = 6;
$bar = $foo;
$bar->bar = 7;
echo $foo->bar . PHP_EOL;
echo $bar->bar . PHP_EOL;
$bar = clone $foo;
$bar->bar = 9;
echo $bar->bar . PHP_EOL;
$hello = new funky();
$hello->bar = 1;
$bar = clone $hello;
echo $bar->bar . PHP_EOL;
11. Make your class follow a contract
<?php
// Declare the interface 'iTemplate'
interface iTemplate
{
public function setVariable($name, $var);
public function getHtml($template);
}
// Implement the interface
// This will work
class Template implements iTemplate
{
private $vars = array();
public function setVariable($name, $var)
{
$this->vars[$name] = $var;
}
public function getHtml($template)
{
foreach($this->vars as $name => $value) {
$template = str_replace('{' . $name . '}', $value, $template);
}
return $template;
}
}
// This will not work
// Fatal error: Class BadTemplate contains 1 abstract methods
// and must therefore be declared abstract (iTemplate::getHtml)
class BadTemplate implements iTemplate
{
private $vars = array();
public function setVariable($name, $var)
{
$this->vars[$name] = $var;
}
}
12. Common base functionality you can extend
<?php
abstract class AbstractClass
ConcreteClass1
{ FOO_ConcreteClass1
// Force Extending class to define this method
abstract protected function getValue(); ConcreteClass2
abstract protected function prefixValue($prefix);
FOO_ConcreteClass2
// Common method
public function printOut() {
print $this->getValue() . "n";
}
}
class ConcreteClass1 extends AbstractClass
{
protected function getValue() {
return "ConcreteClass1";
}
public function prefixValue($prefix) {
return "{$prefix}ConcreteClass1";
}
}
class ConcreteClass2 extends AbstractClass
{
public function getValue() {
return "ConcreteClass2";
}
public function prefixValue($prefix) {
return "{$prefix}ConcreteClass2";
}
}
$class1 = new ConcreteClass1;
$class1->printOut();
echo $class1->prefixValue('FOO_') ."n";
$class2 = new ConcreteClass2;
$class2->printOut();
echo $class2->prefixValue('FOO_') ."n";
13. __sleep and __wakeup say what to serialize,
and what to do on unserialize
__toString is obvious
__set_state works with var_export()
<?php
class MakeMagic {
protected $string;
protected $prefix;
private $cache; O:9:"MakeMagic":2:{s:9:" *
public function __construct($data, $prefix) { string";s:5:"happy";s:9:" *
$this->string = $data;
$this->prefix = $prefix; prefix";s:2:"un";}
$this->cache();
} MakeMagic Object
protected function cache() { (
}
$this->cache = $this->prefix . $this->string; [string:protected] => happy
[prefix:protected] => un
public function __sleep() {
return array('string', 'prefix'); [cache:MakeMagic:private] => unhappy
}
)
public function __wakeup() { unhappy
$this->cache();
} MakeMagic Object
public function __toString() { (
return $this->cache;
} [string:protected] => happy
public static function __set_state($properties) { [prefix:protected] => un
return new self($properties['string'], $properties['prefix']); [cache:MakeMagic:private] => unhappy
}
} )
$class = new MakeMagic('happy', 'un');
$store = serialize($class);
echo $store . PHP_EOL;
$class = unserialize($store);
print_r($class);
echo $class . PHP_EOL;
$string = var_export($class, true);
eval('$test = ' . $string . ';');
print_r($test);
14. Manipulate properties “magically”
Change the way calls are made Setting 'a' to '1'
Getting 'a'
1
<?php
class MemberTest { public function __call($name, $arguments) {
/** Location for overloaded data. */ // Note: value of $name is case sensitive.
private $data = array(); echo "Calling object method '$name' " Is 'a' set?
/** Overloading not used on declared members. */ }
. implode(', ', $arguments). "n"; bool(true)
public $declared = 1; } Unsetting 'a'
/** Overloading only used on this when accessed outsid $obj = new MemberTest; Is 'a' set?
e the class. */
private $hidden = 2; $obj->a = 1; bool(false)
echo $obj->a . "nn";
public function __set($name, $value) {
echo "Setting '$name' to '$value'n";
$this->data[$name] = $value;
var_dump(isset($obj->a));
unset($obj->a);
1
} var_dump(isset($obj->a));
echo "n";
public function __get($name) { Let's experiment with the private
echo "Getting '$name'n"; echo $obj->declared . "nn";
if (array_key_exists($name, $this->data)) { property named 'hidden':
return $this->data[$name]; echo "Let's experiment with the private property named 'hidd Privates are visible inside the
} en':n";
echo "Privates are visible inside the class, so __get() not use class, so __get() not used...
$trace = debug_backtrace(); d...n";
trigger_error( echo $obj->getHidden() . "n"; 2
'Undefined property via __get(): ' . $name . echo "Privates not visible outside of class, so __get() is used.
' in ' . $trace[0]['file'] . ..n"; Privates not visible outside of
' on line ' . $trace[0]['line'], echo $obj->hidden . "n";
E_USER_NOTICE); $obj->runTest('in object context'); class, so __get() is used...
}
return null; Getting 'hidden'
/** As of PHP 5.1.0 */
public function __isset($name) {
echo "Is '$name' set?n";
return isset($this->data[$name]); Notice: Undefined property via
}
__get(): hidden in <file> on line
/** As of PHP 5.1.0 */
public function __unset($name) {
70 in <file> on line 29
echo "Unsetting '$name'n";
unset($this->data[$name]);
} Calling object method 'runTest' in
/** Not a magic method, just here for example. */ object context
public function getHidden() {
return $this->hidden;
}
15. Interfacesand Classes
Encapsulate – don’t pollute the global
namespace
<?php
class MyClass
The value must be a constant expression, not
{ (for example) a variable, a class member, result
const constant = 'constant value'; of a mathematical operation or a function call
function showConstant() { You can’t use define to do class constants
echo self::constant . "n";
}
}
echo MyClass::constant . "n";
$classname = "MyClass";
echo $classname::constant . "n"; // As of PHP 5.
3.0
$class = new MyClass();
$class->showConstant();
echo $class::constant."n"; // As of PHP 5.3.0
16. Autoload magically includes classes/interfaces
when you use them
spl_autoload_register let’s you “stack”
autoloaders
<?php
function __autoload($class_name) {
require_once $class_name . '.php';
}
$obj = new MyClass1();
$obj2 = new MyClass2();
?>
<?php
function my_library_loader($classname) {
static $list;
if (is_null($list)) {
$list = array('myclass', 'yourclass', 'ourclass');
}
if (in_array($classname, $list)) {
include $classname . '.class.php';
}
}
spl_autoload_register('my_library_loader');
spl_autoload_register('__autoload'); // have to explicitly register any __autoload
18. http://php.net/streams
Streams became useable in 4.3 and are
extremely powerful, but still seldom used
Cool new features came along with 5.0+ -
mainly filters and socket support for streams
Two ways to use streams and filters – use the
built in ones or create your own
19. <HTML>
<HEAD>
<TITLE>Example Web Page</TITLE>
</HEAD>
<body>
<p>You have reached this web page by typing
"example.com",
"example.net",
or "example.org" into your web
Available streams will vary – browser.</p>
<p>These domain names are reserved for use in
http, https, tcp, tcps, php documentation and are not available
for registration. See <a href="http://www.rfc-
are usually always present editor.org/rfc/rfc2606.txt">RFC
2606</a>, Section 3.</p>
</BODY>
</HTML>
<?php Array
$options = array( (
'http' => array( [wrapper_data] => Array
'method' => 'POST', (
'header'=> [0] => HTTP/1.1 200 OK
"Accept-language: enrn". [1] => Date: Sun, 07 Sep 2008 15:34:29
"Content-type: application/x-www-form-urlencodedrn", GMT
'content' => http_build_query(array('foo'=>'bar')) [2] => Server: Apache/2.2.3 (CentOS)
)); [3] => Last-Modified: Tue, 15 Nov 2005
13:24:10 GMT
$context = stream_context_create($options); [4] => ETag: "280100-1b6-80bfd280"
[5] => Accept-Ranges: bytes
$fp = fopen('http://www.example.com/', 'r', false, $context); [6] => Content-Length: 438
[7] => Connection: close
$response = stream_get_contents($fp); [8] => Content-Type: text/html;
charset=UTF-8
$meta = stream_get_meta_data($fp); )
[wrapper_type] => http
fclose($fp); [stream_type] => tcp_socket
[mode] => r+
print_r($response); [unread_bytes] => 0
print_r($meta); [seekable] =>
[uri] => http://www.example.com/
?>
[timed_out] =>
[blocked] => 1
[eof] => 1
)
20. Available filters will vary – use stream_get_filters() for a list
GUVF VF N GRFG
<?php GUVF VF N GRFG.
$fp = fopen('php://output', 'w');
stream_filter_append($fp, 'string.rot13');
stream_filter_prepend($fp, 'string.toupper');
fwrite($fp, "This is a test.n");
file_put_contents('php://filter/write=string.rot
13|string.toupper/resource=php://output', "T
his is a test.n");
?>
Some thoughts – this can be very powerful but very difficult to debug
Good places to use streams and filters include templating and text
You can even do transparent encryption and compression
Most of the fancy filter functionality (including custom filters)
is new for PHP5
21. convert_uudecode() - decode a uuencoded string
convert_uuencode() - uuencode a string
file_put_contents() - Write a string to a file
get_declared_interfaces() - Returns an array of all declared interfaces
get_headers() - Fetches all the headers sent by the server in response to a HTTP request
headers_list() - Returns a list of response headers sent (or ready to send)
http_build_query() - Generate URL-encoded query string
image_type_to_extension() - Get file extension for image
imagefilter() - Applies a filter to an image using custom arguments
php_strip_whitespace() - Return source with stripped comments and whitespace
proc_nice() - Change the priority of the current process
setrawcookie() - Send a cookie without URL-encoding the value
scandir() - List files and directories inside the specified path
str_split() - Convert a string to an array
strpbrk() - Search a string for any of a set of characters
substr_compare() - Binary safe optionally case insensitive comparison of two strings from an
offset, up to length characters
error_get_last() - Get the last occurred error as associative array. Returns NULL if there hasn't
been an error yet
memory_get_peak_usage() - Returns the peak allocated by PHP memory
sys_get_temp_dir() - Returns directory path used for temporary files
spl_object_hash() - Return hash id for given object
23. http://php.net/spl
http://www.php.net/~helly/php/ext/spl/
Standard PHP Library – common stuff you’d
use all the time (in C!)
Some neat hooks for additional functionality
you can’t do in PHP userland
Iterators, ArrayAccess, spl_autoload stuff
After5.3 you can’t turn this off (hurrah)
So much to find, I can’t fit it all in this talk
Highlights: ArrayObject, RecursiveFileIterator,
24. Existing Classes - Filtering File Iterator
<?php
class RecursiveFileFilterIterator extends FilterIterator
{
/**
* acceptable extensions - array of strings
*/
protected $ext = array();
/**
* Takes a path and shoves it into our earlier class.
* Turns $ext into an array.
* @param $path directory to iterate
* @param $ext comma delimited list of acceptable extensions
*/
public function __construct($path, $ext = 'php')
{
$this->ext = explode(',', $ext);
parent::__construct(new RecursiveDirectoryIterator($path));
}
/**
* Checks extension names for files only.
*/
public function accept()
{
$item = $this->getInnerIterator();
// If it's not a file, accept it.
if (!$item->isFile()) {
return TRUE;
}
// If it is a file, grab the file extension and see if it's in the array.
return in_array(pathinfo($item->getFilename(), PATHINFO_EXTENSION), $this->ext);
}
}
// Same usage as above, but you can indicate allowed extensions with the optional second argument.
foreach (new RecursiveFileFilterIterator('/path/to/something', 'php,txt') as $item) {
// This is an SPLFileInfo object.
echo $item . PHP_EOL;
}
25. Interfaces - This is your friend
<?php
class User implements ArrayAccess {
private $db; // class to look up users in a db
function offsetExists($name) {
return $this->db->userExists($name);
}
function offsetGet($name) {
return $this->db->getUserId($name);
}
function offsetSet($name, $id) {
$this->db->setUserId($name, $id);
}
function offsetUnset($name) {
$this->db->removeUser($name);
}
}
$userMap = new User();
echo $userMap["Bob"];
26. Foreach fun
rewinding
<?php
class MyIterator implements Iterator
current: 1
{ valid: 1
private $var = array(); current: 1
public function __construct($array) key: 0
{
if (is_array($array)) { 0: 1
$this->var = $array; next: 2
}
} current: 2
valid: 1
public function rewind() {
echo "rewindingn"; current: 2
}
reset($this->var); key: 1
1: 2
public function current() {
$var = current($this->var); next: 3
echo "current: $varn"; current: 3
return $var;
} valid: 1
current: 3
public function key() {
$var = key($this->var); key: 2
echo "key: $varn";
return $var;
2: 3
} next:
public function next() {
current:
$var = next($this->var); valid:
echo "next: $varn";
return $var;
}
public function valid() {
$var = $this->current() !== false;
echo "valid: {$var}n";
return $var;
}
}
$values = array(1,2,3);
$it = new MyIterator($values);
foreach ($it as $a => $b) {
print "$a: $bn";
}
27. http://php.net/pdo
Database Access Layer
Common way to do db connections, different
drivers for different dbs
Doesn’t do SQL abstraction!
28. Basic Usage
<?php
/* Connect to an ODBC database using driver invocation */
$dsn = 'mysql:dbname=testdb;host=127.0.0.1';
$user = 'dbuser';
$password = 'dbpass';
try {
$dbh = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
/* Execute a prepared statement by passing an array of values */
$sql = 'SELECT name, colour, calories
FROM fruit
WHERE calories < :calories AND colour = :colour';
$sth = $dbh->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));
$sth->execute(array(':calories' => 150, ':colour' => 'red'));
$red = $sth->fetchAll();
$sth->execute(array('calories' => 175, 'colour' => 'yellow'));
$yellow = $sth->fetchAll();
29. Advanced Usage
<?php
$stmt = $db->prepare("select foo from bar");
$stmt->execute();
$stmt->setFetchMode(PDO_FETCH_LAZY);
foreach ($stmt as $row) {
echo $row->foo;
}
?>
and the less verbose version:
<?php
foreach ($db->query("select foo from bar", PDO_FETCH_LAZY) as $row) {
echo $row->foo;
}
?>
Blobs:
<?php
$db = new PDO("oci:", "scott", "tiger");
$db->beginTransaction(); // Essential!
$stmt = $db->prepare(
"INSERT INTO blobtest (id, contenttype, blob) ".
"VALUES (:id, :type, EMPTY_BLOB()) ".
"RETURNING blob INTO :blob");
$stmt->bindParam(':id', $id);
$stmt->bindParam(':type', $type);
$stmt->bindParam(':blob', $blob, PDO::PARAM_LOB);
$type = 'image/gif';
$id = 1; // generate your own unique id here
$blob = fopen('/path/to/a/graphic.gif', 'rb');
$stmt->execute();
$stmt->commit();
$stmt = $db->prepare('select blob from blobtest where id = ?');
$stmt->execute(array($id));
$row = $stmt->fetch();
var_dump($row);
var_dump(stream_get_contents($row[0]));
30. http://php.net/mysqli
i means improved (I didn’t name it)
Transactions, prepared statements, the stuff
actually works
Procedural API or OO API (take your pick)
31. Mysql Improved
<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world"); $link = mysqli_connect("localhost", "my_user", "my_password", "world");
/* check connection */ /* check connection */
if (mysqli_connect_errno()) { if (mysqli_connect_errno()) {
printf("Connect failed: %sn", mysqli_connect_error()); printf("Connect failed: %sn", mysqli_connect_error());
exit(); exit();
} }
$city = "Amersfoort"; $city = "Amersfoort";
/* create a prepared statement */ /* create a prepared statement */
if ($stmt = $mysqli- if ($stmt = mysqli_prepare($link, "SELECT District FROM City WHERE Nam
>prepare("SELECT District FROM City WHERE Name=?")) { e=?")) {
/* bind parameters for markers */ /* bind parameters for markers */
$stmt->bind_param("s", $city); mysqli_stmt_bind_param($stmt, "s", $city);
/* execute query */ /* execute query */
$stmt->execute(); mysqli_stmt_execute($stmt);
/* bind result variables */ /* bind result variables */
$stmt->bind_result($district); mysqli_stmt_bind_result($stmt, $district);
/* fetch value */ /* fetch value */
$stmt->fetch(); mysqli_stmt_fetch($stmt);
printf("%s is in district %sn", $city, $district); printf("%s is in district %sn", $city, $district);
/* close statement */ /* close statement */
$stmt->close(); mysqli_stmt_close($stmt);
} }
/* close connection */ /* close connection */
$mysqli->close(); mysqli_close($link);
34. http://php.net/simplexml
XML for dummies <?php
$xmlstr = <<<XML
<?xml version='1.0' standalone='yes'?>
<?php <movies>
include 'example.php'; <movie>
<title>PHP: Behind the Parser</title>
$xml = new SimpleXMLElement($xmlstr); <characters>
<character>
echo $xml->movie[0]->plot; // "So this language. It's like..." <name>Ms. Coder</name>
$xml = new SimpleXMLElement($xmlstr); <actor>Onlivia Actora</actor>
</character>
echo $xml->movie->{'great-lines'}- <character>
>line; // "PHP solves all my web problems" <name>Mr. Coder</name>
<actor>El ActÓr</actor>
$xml = new SimpleXMLElement($xmlstr); </character>
</characters>
/* For each <movie> node, we echo a separate <plot>. */ <plot>
foreach ($xml->movie as $movie) {
echo $movie->plot, '<br />'; So, this language. It's like, a programmin
} g language. Or is it a
scripting language? All is revealed in thi
$xml = new SimpleXMLElement($xmlstr); s thrilling horror spoof
of a documentary.
/* Access the <rating> nodes of the first movie. </plot>
* Output the rating scale, too. */ <great-lines>
foreach ($xml->movie[0]->rating as $rating) { <line>PHP solves all my web problems</line
switch((string) $rating['type']) { // Get attributes
as element indices >
case 'thumbs': </great-lines>
echo $rating, ' thumbs up'; <rating type="thumbs">7</rating>
break; <rating type="stars">5</rating>
case 'stars': </movie>
echo $rating, ' stars'; </movies>
break; XML;
} ?>
}
35. Soap – web services
Sqlite – file based light DB
Reflection – view information about code
DateTime – OO and timezone support for
date manipulation
Dom, xmlreader, and xmlwriter – better ways
to manipulate xml
36. Oooh, shiny buzzword. What we really mean is do more in C
And use Design Patterns – but you knew that…
37. What functionality do What functionality do
you need? you have?
What technologies What technologies do
will you use? you use?
What built in features What can be replaced
can you leverage? with built in features?
New and Shiny Old and Busted
38. Use interfaces, Use “shortcut”
abstract classes, and functions to replace
other OO features to common actions –
lock in patterns like scandir to get a list of
files, file_put_contents
singleton and restrict
visibility Use new extensions to
replace userland
Use SPL features to
implementations – xml
add intelligent parsers, json encoding
iteration or provide and decoding
common functionality
In OO Code In Procedural Code
39. Avoid trying to make PHP act like other
languages
Reflection is nice, using it does not make a good
JAVA style MVC controller
Use PHP5 strengths and avoid weaknesses
json is a good choice for data transfer, xml is
slower but standard, xaml would require either a
PECL extension or a PHP userland parser
Don’t reinvent the wheel
Spl has a recursivedirectoryiterator – use it
http_build_query is quick and safe
use the filter extension for validation or
sanitizing
40. Use of SAX xml parsers – xmlreader is your
friend
Json encoders/decoders
Crufty ways of doing singletons, abstract
classes, private/protected by naming
conventions, CLASSNAME_CONSTANTNAME
constants
Add features (like encryption) without
messing up old code with streams and filters
Throw out crazy custom array code and use
the built in stuff – array_combine rocks
41. Remember – C is faster than PHP
You don’t have to use all the PHP5
features, but don’t use hacks to fake
them either
You don’t have to use OOP, but don’t
complete shun it on principle.
Writing an extensive function to filter
the results of a scandir array is silly
when you can use
RecursiveDirectoryIterator
42. What version of PHP should be on your
server?
Why?
What’s the one thing to remember from this
talk?
What does that mean when thinking about
writing code?
What’s my favorite color?
And what color are these slides?
43. Name some magic methods in PHP
What should you never use to prefix your own
methods?
How do you copy a PHP5 object
What does “deep copy” mean and why is it
problematic in PHP5?
Howcan you have more than one __autoload
methods?
What’s the one thing to remember when using an
spl autoload stack?
44. What is a stream?
Name two common PHP streams
What is a filter
How do you use filters with file_get_contents
What is your favorite new function in PHP5?
Why?
Why is preg_last_error useful?
How much do you like regex ;)
Name one new header function
Halfway there…
45. What does mysqli provide that mysql does
not?
What does the I stand for.
What extension can you use to validate and
sanitize data?
What extension is very useful with
xmlhttprequest?
How can you control what properties of an
object are shown with foreach?
What interface do you have to use to do this?
46. Name one PHP4 hack no longer needed in
PHP5
Why isn’t it needed? How would you replace it?
Name one technology you’d use in a new
project because of improved PHP5 support
Would you use a different one if PHP5 had better
support?
What is the difference between how you
approach designing a new project, and
redoing parts of a legacy project?
How are they the same?