Modern PHP
Namespaces
- encapsulates and organises related PHP classes
- separated with \
- prevent name collisions
- top -level vendor name
Oreilly
- sub namespace
Oreilly\ModernPHP
- namespace without alias
new \Symfony\Component\HttpFoundation\Response('Oops', 400);
- can use an alias
use zzzzz as Res;
Autoloading
Interfaces
Traits
- use a trait when tow unrelated classes need to exhibit similar behavior.
Generators
Generators are simple iterators.
- generators compute and yield iteration values on demand
- why user? - saves memory
Closures
- closure a function that encapsulates it’s surrounding state at the time it is created
Chapter 3 Standards
Sanitize
$input = '<p><script>alert("You won the Nigerian lottery!");</script></p>';
echo htmlentities($input, ENT_QUOTES, 'UTF-8');
use filter_var
for email address etc.
PHP Objects, Patterns, and Practice
##Part 3 - Object Basics
Invoking an Overridden Method
Extending the parent method:
// ShopProduct class...
function getSummaryLine()
{
$base = "{$this->title} ( {$this->producerMainName}, ";
$base .= "{$this->producerFirstName} )";
return $base;
}
// BookProduct class...
function getSummaryLine()
{
$base = parent::getSummaryLine();
$base .= ": page count - {$this->numPages}";
return $base;
}
Chapter 4 Advanced Features
static
allows you to access the methods and properties of the class (not object).- use
self
to access from the object itself (like $this is for objects)
Late Static Binding
- static methods can be used as factories
- static refers to the invoked, rather than the containing class
This means that you can do this in the base class:
abstract class DomainObject
{
public static function create() {
return new static();
}
and you will actually get a child class (assuming that Document extends DomainObject):
Document::create();
- final prevents inheritance:
final class Checkout
Working with Interceptors (overloading)
__get() and __set()
are using for getting and setting properties which don’t exist
class Person {
function __get( $property ) {
$method = "get{$property}";
if ( method_exists( $this, $method ) ) {
return $this->$method();
}
}
Clone
- used to copy and objext
Callbacks, Anonymous Functions and Closures
Class and Object Functions;
- getClass()
- getClassMethods()
- getClassVars()
- getParentClass()
The Reflection API
Part 3 Patterns
Composition and Inheritance
Using Composition - The Strategy Pattern
- Strategy is used to move a set of algorithms into a separate type.
Singleton Pattern
Factory
function getApptEncoder() {
switch ( $this->mode ) {
case ( self::MEGA ):
return new MegaApptEncoder();
default:
return new BloggsApptEncoder();