Create your own PHP extension, step by step - phpDay 2012 VeronaPatrick Allaert
Ever been interested by contributing to the PHP core team?
In this workshop you will not only learn how (easy it is) to create your own PHP extension from scratch but you will also strengthen your knowledge of PHP by disecting its internals.
After this workshop, you will be able to create an extension on your own, whether it is to optimize the most CPU intensive parts of your code, to create new bindings to C libraries or just to leverage your PHP knowledge.
And what if PHP was a web framework for the C developer?
This workshop requires a bit of C knowledge and preferably a *nix system.
Create your own PHP extension, step by step - phpDay 2012 VeronaPatrick Allaert
Ever been interested by contributing to the PHP core team?
In this workshop you will not only learn how (easy it is) to create your own PHP extension from scratch but you will also strengthen your knowledge of PHP by disecting its internals.
After this workshop, you will be able to create an extension on your own, whether it is to optimize the most CPU intensive parts of your code, to create new bindings to C libraries or just to leverage your PHP knowledge.
And what if PHP was a web framework for the C developer?
This workshop requires a bit of C knowledge and preferably a *nix system.
PECL Picks - Extensions to make your life betterZendCon
One of the biggest strengths of PHP is its "glue" power. Take any C library and with a little magic and a compiler you have a fantastic extension. These extensions hide in PECL, but few people can tell the good from the unmaintained or just plain broken. Find the best extensions for your project, learn about PECL, and find out how to become a part of the PECL developer community.
Doctrine 2.0 Enterprise Persistence Layer for PHPGuilherme Blanco
One area that was mostly abandoned in applications is the Model layer. Doctrine is a project that brings enterprise support this layer through a powerful ORM implementation.
Allied with new support introduced in PHP 5.3, Doctrine 2.0 brings the concept of ORM in PHP to the next level. It introduces a couple of concepts known from other languages and areas, like Annotations, Object Query Languages and Parsers. This talk will introduce these new concepts as well as explain most of its architecture.
Diving into HHVM Extensions (PHPNW Conference 2015)James Titcumb
HHVM is currently gaining popularity at quite a pace, and it's a pretty exciting time for PHP runtimes. Have you ever wondered what is going on beneath this slick and super-speedy engine? I wondered that myself, so I dived into the internals of HHVM, discovering a treasure trove of awesome stuff. In this talk, I'll show you how HHVM itself works with a guided tour of the codebase, demonstrating how it all pieces together. I'll also show you a couple of ways to write your own incredible HHVM extension. You don't need to know C++ to understand this talk - just PHP language knowledge is enough.
Visual guide to selling software as a service by @prezlyPrezly
It took my team years to find an efficient way of getting new customers. First, I’ll show you how we messed up and then how we got on the road to conversion success using the pirate metrics framework.
PECL Picks - Extensions to make your life betterZendCon
One of the biggest strengths of PHP is its "glue" power. Take any C library and with a little magic and a compiler you have a fantastic extension. These extensions hide in PECL, but few people can tell the good from the unmaintained or just plain broken. Find the best extensions for your project, learn about PECL, and find out how to become a part of the PECL developer community.
Doctrine 2.0 Enterprise Persistence Layer for PHPGuilherme Blanco
One area that was mostly abandoned in applications is the Model layer. Doctrine is a project that brings enterprise support this layer through a powerful ORM implementation.
Allied with new support introduced in PHP 5.3, Doctrine 2.0 brings the concept of ORM in PHP to the next level. It introduces a couple of concepts known from other languages and areas, like Annotations, Object Query Languages and Parsers. This talk will introduce these new concepts as well as explain most of its architecture.
Diving into HHVM Extensions (PHPNW Conference 2015)James Titcumb
HHVM is currently gaining popularity at quite a pace, and it's a pretty exciting time for PHP runtimes. Have you ever wondered what is going on beneath this slick and super-speedy engine? I wondered that myself, so I dived into the internals of HHVM, discovering a treasure trove of awesome stuff. In this talk, I'll show you how HHVM itself works with a guided tour of the codebase, demonstrating how it all pieces together. I'll also show you a couple of ways to write your own incredible HHVM extension. You don't need to know C++ to understand this talk - just PHP language knowledge is enough.
Visual guide to selling software as a service by @prezlyPrezly
It took my team years to find an efficient way of getting new customers. First, I’ll show you how we messed up and then how we got on the road to conversion success using the pirate metrics framework.
Kicking the Bukkit: Anatomy of an open source meltdownRyanMichela
On September 3rd, 2014, a disgruntled ex-developer erased from the internet the work of over 150 developers over four years. This is the story of the Bukkit Minecraft server project's demise, and how you protect your project from its fate.
Presented at Silicon Valley Code Camp 2014: http://www.siliconvalley-codecamp.com/Session/2014/kicking-the-bukkit-anatomy-of-an-open-source-meltdown
Performance and testing are just one aspect of code, to really be successful your code needs to be readable, maintainable and generally easier to comprehend and work with. This talk draws from my own experience in applying the techniques of object calisthenics and code readability, within an existing team. It will help you identify trouble areas, learn how to refactor them and train you to write better code in future projects avoiding common pitfalls.
React is a different way to write JavaScript apps. When it was introduced at JSConf US in May, the audience was shocked by some of its design principles. One sarcastic tweet from an audience member ended up describing React’s philosophy quite accurately: https://twitter.com/cowboy/status/339858717451362304
We’re trying to push the limits of what’s possible on the web with React. My talk will start with a brief introduction to the framework, and then dive into three controversial topics: Throwing out the notion of templates and building views with JavaScript, “re-rendering” your entire application when your data changes, and a lightweight implementation of the DOM and events.
Presentation made at GTA meetup in 2012-02-07.
Object Calisthenics is a set of exercise rules to reach better code, maintainable, testable and readable.
Composer has triggered a renaissance in the PHP community, it has changed the way we deal with other people’s code and it has changed the way we share our code. We are all slowly moving to using Composer, from Wordpress to Joomla and Drupal and frameworks in between. But many of us mistreat composer, follow outdated practices or simply lack a few tricks. In this session i’ll get you the low down on how to use composer the right way.
s React.js a library or a framework? In any case, it is a new way of working that represents a revolution in the way of building web projects. It has very particular characteristics that allow us, for instance, to render React code from the server side, or to include React components from Twig tags. During this talk we will present React.js, we will explore how to take advantage of it from PHP projects and we will give answers to practical problems such as universal (isomorphical) rendering and the generation of React.js forms from Symfony forms without duplication of efforts.
MySQL users commonly ask: Here's my table, what indexes do I need? Why aren't my indexes helping me? Don't indexes cause overhead? This talk gives you some practical answers, with a step by step method for finding the queries you need to optimize, and choosing the best indexes for them.
Enterprise PHP: mappers, models and servicesAaron Saray
One of the greatest failures PHP has is not that it is a bad language, but that it isn't marketed as a good language. Since it's so easy to do it bad, a lot of people do just that. However, there is hope. Businesses ARE using PHP for Enterprise! You just need to apply a solid foundation to the language to get to that Enterprise level.
With our mind on the Enterprise sphere, it's time to take PHP programming to a more advanced level. To get the most out of this talk, you should already be familiar with object oriented programming concepts in PHP. To begin with, I'll talk about the need for a service layer, data mappers, and business object models. Then I'll demonstrate examples of how to do it right. As an added bonus, I'm not going to just tell you why it's best practice and a "good idea" - I'm going to SHOW you. This might be the first time in your life that you realize that changes in architecture, supporting infrastructure, and business requirements don't have to be as painful as you once thought!
From development environments to production deployments with Docker, Compose,...Jérôme Petazzoni
In this session, we will learn how to define and run multi-container applications with Docker Compose. Then, we will show how to deploy and scale them seamlessly to a cluster with Docker Swarm; and how Amazon EC2 Container Service (ECS) eliminates the need to install,operate, and scale your own cluster management infrastructure. We will also walk through some best practice patterns used by customers for running their microservices platforms or batch jobs. Sample code and Compose templates will be provided on GitHub afterwards.
Enterprise PHP Architecture through Design Patterns and Modularization (Midwe...Aaron Saray
Object Oriented Programming in enterprise level PHP is incredibly important. In this presentation, concepts like MVC architecture, data mappers, services, and domain and data models will be discussed. Simple demonstrations will be used to show patterns and best practices. In addition, using tools like Doctrine or integration with Salesforce or the AS/400 will also be discussed. There will be an emphasis on the practical application of these techniques as well - this isn't just a theoretical talk! This presentation is great for those just beginning to create enterprise applications as well as those who have had years of experience.
(video of these slides available here http://fsharpforfunandprofit.com/fppatterns/)
In object-oriented development, we are all familiar with design patterns such as the Strategy pattern and Decorator pattern, and design principles such as SOLID.
The functional programming community has design patterns and principles as well.
This talk will provide an overview of some of these, and present some demonstrations of FP design in practice.
From Idea to Execution: Spotify's Discover WeeklyChris Johnson
Discover Weekly is a personalized mixtape of 30 highly personalized songs that's curated and delivered to Spotify's 75M active users every Monday. It's received high acclaim in the press and reached 1B streams within its first 10 weeks. In this slide deck we dive into the narrative of how Discover Weekly came to be, highlighting technical challenges, data driven development, and the Machine Learning models used to power our recommendations engine.
Talk for SCaLE13x. Video: https://www.youtube.com/watch?v=_Ik8oiQvWgo . Profiling can show what your Linux kernel and appliacations are doing in detail, across all software stack layers. This talk shows how we are using Linux perf_events (aka "perf") and flame graphs at Netflix to understand CPU usage in detail, to optimize our cloud usage, solve performance issues, and identify regressions. This will be more than just an intro: profiling difficult targets, including Java and Node.js, will be covered, which includes ways to resolve JITed symbols and broken stacks. Included are the easy examples, the hard, and the cutting edge.
Object Trampoline: Why having not the object you want is what you need.Workhorse Computing
Overview of Trampoline Objects in Perl with examples for lazy construction, lazy module use, added sanity checks. This version includes corrections from the original presented at OSCON 2013 and comments.
It contains different concepts of Object Oriented PHP like cloning of object, Inheritance, function overriding, Final function, Error Handling, Exception Handling, Custom error handling class, Uploading a file to the server with different criteria like file size, file type, file extension etc. are discussed in this presentation.
Kindly look at it and give comments to improve it as good as possible ways.
The recent Project of the Month on SourceForge, XOOPS (http://www.xoops.org) was designed from the very beginning as an object-oriented CMS, which is even reflected in its name: eXtensible Object Oriented Portal System. Michael will present the OOP oriented architecture of XOOPS, and show how OOP makes development of XOOPS modules easy and fun, promotes reuse of code, while keeping GUI consistent across all modules.
Apache est le serveur Web le plus utilisé sur la planète. Né en 1995, Apache HTTPD est aujourd'hui massivement utilisé pour supporter des applications PHP.
Cependant, peu de développeurs connaissent vraiment cette machine aussi complexe que robuste qui supporte leur langage fétiche : PHP.
Il n'est pas rare de voir des codes PHP exécutant des actions qu'Apache sait gérer en une seule ligne, de manière beaucoup plus efficace.
Nous parlerons donc généralités, HTTP, Cache, Proxing et nous passerons en revue les différentes manière de coupler Apache à PHP (mod_php, CGI et FCGI, mais aussi mpm_peruser, mpm_itk, suexec, suphp).
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...DanBrown980551
Do you want to learn how to model and simulate an electrical network from scratch in under an hour?
Then welcome to this PowSyBl workshop, hosted by Rte, the French Transmission System Operator (TSO)!
During the webinar, you will discover the PowSyBl ecosystem as well as handle and study an electrical network through an interactive Python notebook.
PowSyBl is an open source project hosted by LF Energy, which offers a comprehensive set of features for electrical grid modelling and simulation. Among other advanced features, PowSyBl provides:
- A fully editable and extendable library for grid component modelling;
- Visualization tools to display your network;
- Grid simulation tools, such as power flows, security analyses (with or without remedial actions) and sensitivity analyses;
The framework is mostly written in Java, with a Python binding so that Python developers can access PowSyBl functionalities as well.
What you will learn during the webinar:
- For beginners: discover PowSyBl's functionalities through a quick general presentation and the notebook, without needing any expert coding skills;
- For advanced developers: master the skills to efficiently apply PowSyBl functionalities to your real-world scenarios.
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf91mobiles
91mobiles recently conducted a Smart TV Buyer Insights Survey in which we asked over 3,000 respondents about the TV they own, aspects they look at on a new TV, and their TV buying preferences.
GraphRAG is All You need? LLM & Knowledge GraphGuy Korland
Guy Korland, CEO and Co-founder of FalkorDB, will review two articles on the integration of language models with knowledge graphs.
1. Unifying Large Language Models and Knowledge Graphs: A Roadmap.
https://arxiv.org/abs/2306.08302
2. Microsoft Research's GraphRAG paper and a review paper on various uses of knowledge graphs:
https://www.microsoft.com/en-us/research/blog/graphrag-unlocking-llm-discovery-on-narrative-private-data/
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...UiPathCommunity
💥 Speed, accuracy, and scaling – discover the superpowers of GenAI in action with UiPath Document Understanding and Communications Mining™:
See how to accelerate model training and optimize model performance with active learning
Learn about the latest enhancements to out-of-the-box document processing – with little to no training required
Get an exclusive demo of the new family of UiPath LLMs – GenAI models specialized for processing different types of documents and messages
This is a hands-on session specifically designed for automation developers and AI enthusiasts seeking to enhance their knowledge in leveraging the latest intelligent document processing capabilities offered by UiPath.
Speakers:
👨🏫 Andras Palfi, Senior Product Manager, UiPath
👩🏫 Lenka Dulovicova, Product Program Manager, UiPath
Transcript: Selling digital books in 2024: Insights from industry leaders - T...BookNet Canada
The publishing industry has been selling digital audiobooks and ebooks for over a decade and has found its groove. What’s changed? What has stayed the same? Where do we go from here? Join a group of leading sales peers from across the industry for a conversation about the lessons learned since the popularization of digital books, best practices, digital book supply chain management, and more.
Link to video recording: https://bnctechforum.ca/sessions/selling-digital-books-in-2024-insights-from-industry-leaders/
Presented by BookNet Canada on May 28, 2024, with support from the Department of Canadian Heritage.
JMeter webinar - integration with InfluxDB and GrafanaRTTS
Watch this recorded webinar about real-time monitoring of application performance. See how to integrate Apache JMeter, the open-source leader in performance testing, with InfluxDB, the open-source time-series database, and Grafana, the open-source analytics and visualization application.
In this webinar, we will review the benefits of leveraging InfluxDB and Grafana when executing load tests and demonstrate how these tools are used to visualize performance metrics.
Length: 30 minutes
Session Overview
-------------------------------------------
During this webinar, we will cover the following topics while demonstrating the integrations of JMeter, InfluxDB and Grafana:
- What out-of-the-box solutions are available for real-time monitoring JMeter tests?
- What are the benefits of integrating InfluxDB and Grafana into the load testing stack?
- Which features are provided by Grafana?
- Demonstration of InfluxDB and Grafana using a practice web application
To view the webinar recording, go to:
https://www.rttsweb.com/jmeter-integration-webinar
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...James Anderson
Effective Application Security in Software Delivery lifecycle using Deployment Firewall and DBOM
The modern software delivery process (or the CI/CD process) includes many tools, distributed teams, open-source code, and cloud platforms. Constant focus on speed to release software to market, along with the traditional slow and manual security checks has caused gaps in continuous security as an important piece in the software supply chain. Today organizations feel more susceptible to external and internal cyber threats due to the vast attack surface in their applications supply chain and the lack of end-to-end governance and risk management.
The software team must secure its software delivery process to avoid vulnerability and security breaches. This needs to be achieved with existing tool chains and without extensive rework of the delivery processes. This talk will present strategies and techniques for providing visibility into the true risk of the existing vulnerabilities, preventing the introduction of security issues in the software, resolving vulnerabilities in production environments quickly, and capturing the deployment bill of materials (DBOM).
Speakers:
Bob Boule
Robert Boule is a technology enthusiast with PASSION for technology and making things work along with a knack for helping others understand how things work. He comes with around 20 years of solution engineering experience in application security, software continuous delivery, and SaaS platforms. He is known for his dynamic presentations in CI/CD and application security integrated in software delivery lifecycle.
Gopinath Rebala
Gopinath Rebala is the CTO of OpsMx, where he has overall responsibility for the machine learning and data processing architectures for Secure Software Delivery. Gopi also has a strong connection with our customers, leading design and architecture for strategic implementations. Gopi is a frequent speaker and well-known leader in continuous delivery and integrating security into software delivery.
UiPath Test Automation using UiPath Test Suite series, part 4DianaGray10
Welcome to UiPath Test Automation using UiPath Test Suite series part 4. In this session, we will cover Test Manager overview along with SAP heatmap.
The UiPath Test Manager overview with SAP heatmap webinar offers a concise yet comprehensive exploration of the role of a Test Manager within SAP environments, coupled with the utilization of heatmaps for effective testing strategies.
Participants will gain insights into the responsibilities, challenges, and best practices associated with test management in SAP projects. Additionally, the webinar delves into the significance of heatmaps as a visual aid for identifying testing priorities, areas of risk, and resource allocation within SAP landscapes. Through this session, attendees can expect to enhance their understanding of test management principles while learning practical approaches to optimize testing processes in SAP environments using heatmap visualization techniques
What will you get from this session?
1. Insights into SAP testing best practices
2. Heatmap utilization for testing
3. Optimization of testing processes
4. Demo
Topics covered:
Execution from the test manager
Orchestrator execution result
Defect reporting
SAP heatmap example with demo
Speaker:
Deepak Rai, Automation Practice Lead, Boundaryless Group and UiPath MVP
Generating a custom Ruby SDK for your web service or Rails API using Smithyg2nightmarescribd
Have you ever wanted a Ruby client API to communicate with your web service? Smithy is a protocol-agnostic language for defining services and SDKs. Smithy Ruby is an implementation of Smithy that generates a Ruby SDK using a Smithy model. In this talk, we will explore Smithy and Smithy Ruby to learn how to generate custom feature-rich SDKs that can communicate with any web service, such as a Rails JSON API.
Connector Corner: Automate dynamic content and events by pushing a buttonDianaGray10
Here is something new! In our next Connector Corner webinar, we will demonstrate how you can use a single workflow to:
Create a campaign using Mailchimp with merge tags/fields
Send an interactive Slack channel message (using buttons)
Have the message received by managers and peers along with a test email for review
But there’s more:
In a second workflow supporting the same use case, you’ll see:
Your campaign sent to target colleagues for approval
If the “Approve” button is clicked, a Jira/Zendesk ticket is created for the marketing design team
But—if the “Reject” button is pushed, colleagues will be alerted via Slack message
Join us to learn more about this new, human-in-the-loop capability, brought to you by Integration Service connectors.
And...
Speakers:
Akshay Agnihotri, Product Manager
Charlie Greenberg, Host
Securing your Kubernetes cluster_ a step-by-step guide to success !KatiaHIMEUR1
Today, after several years of existence, an extremely active community and an ultra-dynamic ecosystem, Kubernetes has established itself as the de facto standard in container orchestration. Thanks to a wide range of managed services, it has never been so easy to set up a ready-to-use Kubernetes cluster.
However, this ease of use means that the subject of security in Kubernetes is often left for later, or even neglected. This exposes companies to significant risks.
In this talk, I'll show you step-by-step how to secure your Kubernetes cluster for greater peace of mind and reliability.
2. Hello everybody
Julien PAULI
Programming in PHP since ~10y
PHP Internals reviewer
PHP 5.5 and 5.6 Release Manager or Co-RM
Working at SensioLabs in Paris
http://www.phpinternalsbook.com
@julienpauli - github.com/jpauli - jpauli@php.net
3. What we'll cover together
Covering PHP 5 only
Quick recall on zvals
Object structures internally
zend_object_value
zend_class_entry
zend_object_handlers
zend_object_store
PHP objects lifecycle
Creating and destroying an object
Memory management & garbage collection
5. Zvals
PHP variables can carry several types
PHP is not strongly typed
Type juggling
Internally, all variables are represented into a
container which can carry all supported PHP
types : "zval"
8. zvals refcount
Every PHP variable is a zval :
PHP does not duplicate memory when you
duplicate variables in the same scope
It plays with the refcount of the zval
refcount is how many variables point to the zval
<?php
$o = new MyClass;
<?php
$o = new MyClass; // refcount = 1
$o2 = $o; // refcount = 2
9. zvals refcount
The zval is automatically freed when refcount
reaches zero, and never before
When a zval is freed, its content is freed if not
shared elsewhere
In our case : an object
<?php
$o = new MyClass; // refcount = 1
$o2 = $o; // refcount = 2
unset($o); // refcount = 1, zval is not freed
unset($o2); // refcount = 0, zval is freed
10. Statement
Objects are variables
Variables are zvals
Objects are not freed until their zval's refcount
reaches zero
12. PHP Objects ?
Objects are zvals of type IS_OBJECT
The value field used is "obj" in the zval
zend_object_value type
13. PHP objects details
An object carries :
A handle
Some handlers
The handle is a unique integer designed to
fetch the "real" object from an internal store
16. Objects are NOT references
Simple proof
function foo($var) {
$var = 42;
}
$o = new MyClass;
foo($o);
var_dump($o);
object(MyClass)#1 (0) {
}
17. Objects borrow ref. behavior
Because each variable (zval) encapsulates the
same object handle
function foo($var) {
$var->name = 'foo';
}
$o = new MyClass;
$o->name = 'bar';
foo($o);
var_dump($o);
object(MyClass)#1 (0) {
public $name =>
string(3) "foo"
}
18. zvals vs object handles
This writes to the zval container $object :
This changes the zval value
Before it was an object, now it's a string
The object that was into it has never been changed here
This fetches the object using its handle, and
writes to that object :
All other zvals using this same object handle are
affected, whatever their scope
$object = 'overwritten';
$object->var = 'changed';
19. Creating a new object
The two only ways to create a new object in the
store are :
new keyword (unserialize() may use new as well)
clone keyword
$o = new MyClass;
$a = $o;
$a->name = 'foo';
$b = clone $a;
$c = $b;
$b->name = 'bar';
$a = 'string';
Object#1
name => "foo"
Object#1
name => "bar"
zval1
obj_handle => #1
Object#1
name => "bar"
zval2
'string'$b
$o
object storezval storesym tables
$a
$c zval3
obj_handle => #2
Object#2
name => "bar"
20. zval duplication with objects
Even when you force PHP to duplicate a zval, if it represents an
object, this latter won't be copied :
This is PHP5 behavior
The objects are not duplicated, weither you use PHP references or not
Zvals may get duplicated (if you abuse PHP references usage !)
Objects themselves also carry a refcount
$o = new MyClass;
$a = &$o; // take a reference
/* Force PHP to duplicate the zval */
$b = $a;
/* We all agree that here, modifying $a or $b or $o
will modify the *same* object */
21. zval duplication and objects
Even if you force PHP to dup. a zval container,
the object stored in it won't be dup.
$o = new MyClass;
$a = &$o;
$a->name = 'foo';
$b = $a;
Object#1
name => "foo"
Object#1
name => "bar"
zval1
obj_handle => #1
$b
$o
object storezval storesym tables
$a
zval2
obj_handle => #1
22. First step conclusion
Having lots of variables pointing to the same
object is not bad for memory usage
"clone", "new" and "unserialize" are the only
ways to create an object in the store
Thus to consume more memory
To free (destroy) an object from memory, one
must destroy all zvals in all scopes pointing to
it
Keeping track of this can be hard
use xdebug, master your code, remember
25. Statements :
PHP garbage collector is NOT object specific
It is zval based (any PHP type so)
PHP GC is a circular references GC
It's only goal is to free unfetchable circular
references from userland
PHP has always freed unused zvals of which
refcount reached zero
GC has nothing to do with this behavior
PHP Circular references GC appeared in 5.3
28. Some circ.ref. cleaned by GC
$a = new StdClass;
$b = new StdClass;
$a->b = $b;
$b->a = $a;
unset($a,$b);
echo gc_collect_cycles(); // 2
29. Objects circ.ref are common
It is very easy to create a
circ.ref leak with objects
This will have an impact if :
Your objects are "heavy"
You run long living process
Ex are some SF2 commands
... with doctrine 2
class A
{
private $b;
function __construct() {
$this->b = new B($this);
}
}
class B
{
private $a;
function __construct(A $a) {
$this->a = $a;
}
}
$a = new A;
unset($a);
31. zend_object type
Objects in PHP are zend_object
Objects live in a global "store"
They are indexed using their unique handle
As we've seen, PHP does all it can do not to
duplicate the object into the store
Only way to duplicate : "clone"
32. zend_class_entry
Represents a PHP class
or an interface
By far the biggest
structure !
This structure's been
shrinked to fit the slide
The structure size is
~500 bytes
33. Object memory consumption
Object declared attributes are stored once in the class
structure at compile time
When you create an object (new), PHP will duplicate
the zval attributes from the class to the object
The object now effectively owns its own copy of attributes
zvals pointers are copied, not zval values. COW still effective
Conclusion : An object weight is directly bound to its
attributes weight
As class informations are shared between objects
34. Object memory consumption
Every declared property is stored in the class structure
They are stored with info structures
Those also consume memory
The class also embeds
Its own static properties
its own constants
an array of interfaces it implements
an array of traits it uses
more info
class consumes much more memory than an object
But the same class is shared between all its children objects
35. Lifetimes
Objects start living when you create them and
stop living when they are destroyed
when the last zval pointing to the object is destroyed
Classes start living when PHP starts parsing a
T_CLASS (class {) token
Classes stop living when PHP shuts down (end
of request)
Every class info, e.g its static members, have a
lifetime of the class itself
unset(MyClass::$variable);
Fatal error: Attempt to unset static property
38. Object handlers
Every single tiny operation on objects is done
using a handler (a redefinable function)
For example
calling a method on an object
Fetching an object property
But also :
Casting an object (zend_object_cast_t)
Comparing an object with something (zend_object_compare_t)
...
42. Overriding object handlers
You should know about "special behaving PHP
objects" don't you ?
SimpleXmlElement
PDOStatement
DateTime
...
They all redefine default handlers
43. And from PHP land ?
You may overwrite some handlers from PHP
Land
ArrayAccess
Serializable
Countable
Designing a PHP extension, you may overwrite
any handler you want
That's great
Customize PHP object behavior
45. construct. params strangeness
Please, explain that behavior :
new StdClass($a=5);
var_dump($a);
PHP Notice : undefined variable $a
new DateTime($a='now');
var_dump($a);
string(3) "now"
46. Destructor secrets
__destruct() is called when an object is
destroyed
Destroyed == freeed (often)
Reminder : An object is destroyed when no
more zvals point to it
$a = new SomeClass; // refcount = 1
/* calls __destruct() */
unset($a); // refcount reaches 0
47. Destructor secrets
Let's now see what happens at shutdown
When you don't destruct your objects yourself
That's bad, you'll see
When you leave PHP's shutdown clean your objects
Yes, that's bad
$a = new SomeClass; // refcount = 1
/* Shutdown sequence */
49. Shutdown and destructors #1
PHP will loop backward the global symbol table
and destroy objects which zval's refcount = 1
Last object created = first cleared
1 2 3
class Foo { public function __destruct() { var_dump("Destroyed Foo"); } }
class Bar { public function __destruct() { var_dump("Destroyed Bar"); } }
$a = new Foo,
$b = new Bar;
$a = new Bar,
$b = new Foo;
"Destroyed Bar"
"Destroyed Foo"
"Destroyed Foo"
"Destroyed Bar"
$a = new Bar,
$b = new Foo;
$c = $b;
"Destroyed Bar"
"Destroyed Foo"
50. Shutdown and destructors #2
Then (for objects where refcount > 1) PHP will
loop forward the object store and destroy all
objects
In order of their creation so (forward)
$a = new Foo;
$a2 = $a;
$b = new Bar;
$b2 = $b;
"Destroyed Foo"
"Destroyed Bar"
51. Shutdown and destructors #3
If a destructor exit()s or die()s, the other
destructors are not executed
But the objects are "marked as destructed"
$a = new Foo;
$a2 = $a;
$b = new Bar;
$b2 = $b;
"Destroyed Foo"
class Foo { public function __destruct() { var_dump("Destroyed Foo"); die(); } }
class Bar { public function __destruct() { var_dump("Destroyed Bar"); } }
52. __destruct() weirdness
So, knowing that, we can meet weird behaviors
class Foo
{
public $state = 'alive';
function __destruct() {
$this->state = 'destructed';
}
}
class Bar
{
public $foo;
function __destruct() {
var_dump($this->foo->state);
}
}
$foo = new Foo;
$bar = new Bar;
$bar->foo = $foo;
$foo = new Foo;
$bar = new Bar;
$bar->foo = $foo;
$a = $bar;
"alive"
"destructed"
53. "Destroying" an object
When you destroy an object, PHP will
immediatly free it
When PHP destroys an object during shutdown
sequence, it will only call __destruct() and will
not free the object immediately
That's why you can reuse "destroyed" objects
See preceding slide
The objects will be freed when the engine will
shutdown
$a = new SomeClass;
unset($a);
54. __destruct() in shutdown
PHP's shutdown sequence is clear
http://lxr.php.net/xref/PHP_5_4/main/main.c#1728
1. call shutdown functions
2. call object destructors
3. end output buffering
4. shutdown all extensions
5. destroy superglobals
6. shutdown scanner/executor/compiler
Frees object storage
Every object handling done after phase #2 can
lead to weird behavior and/or crash PHP
55. A great conclusion of this
Don't rely on PHP's shutdown behavior
It has changed throughout PHP versions
It will change in the future
It can make PHP hang or crash in worst cases
Just destroy and free the resources yourself !
56. function stack serialized
serializing an Exception serializes its stack trace
Which itself could be not serializable ...
function foo(SimpleXMlElement $x, $a)
{
echo serialize(new Exception());
}
foo(new SimpleXmlElement('<a />'), 'a');
Fatal error: Uncaught exception 'Exception' with message
'Serialization of 'SimpleXMLElement' is not allowed'
57. Class Early Binding
Early binding = compiler declares solo classes
Inheritence is honnored at runtime
Conditionnal declarations are honnored at runtime
Declare your classes in the "right" order
Use runtime autoloader
class C extends B {}
class B extends A {}
class A {}
Fatal error: Class 'B' not found
class C extends A {}
class A {}
/* all right */