Upload
others
View
2
Download
0
Embed Size (px)
Citation preview
PHP 5 and the new OO features for enterprise
solutions, part 1Marcus Börger
international PHP2003 conference
Marcus Börger PHP5 2
Overview
PHP5 vs PHP4
Is PHP5 revolutionary?
PHP 5 OOWhy is OO a good thing?
Marcus Börger PHP5 3
Revamped OO Model
PHP5 has really good OOBetter code reuseBetter for team developmentEasier to refactorSome patterns lead to much more efficient codeFits better in marketing scenarios
Marcus Börger PHP5 4
PHP 4 and OO ?
Poor Object modelMethods
No visibilityNo abstracts, No finalStatic without declaration
PropertiesNo default valuesNo static properties
InheritanceNo abstract, final inheritance, no interfaces
Object handlingCopied by valueNo destructors
Marcus Börger PHP5 5
ZE2's revamped object modelObjects are referenced by identifiersConstructors and DestructorsStatic membersDefault property valuesConstantsVisibilityInterfacesFinal and abstract membersInterceptorsExceptionsReflection APIIterators
Marcus Börger PHP5 6
Objects are no longer copied by defaultObjects may be copied using __clone()
<?php
class Object {};
$obj = new Object();
$ref = $obj;
$dup = $obj->__clone();
?>
Objects referenced by identifiers
Class Object
$obj $ref $dup
Instance 1 Instance 2
Marcus Börger PHP5 7
Constructors/Destructors control object lifetimeConstructors may have both new OR old style namesDestructors are called when deleting last reference
<?php
class Object {function __construct() {}function __destruct() {}
}$obj = new Object();unset($obj);
?>
Constructors and Destructors
Marcus Börger PHP5 8
Parents must be called manually
<?phpclass Base {
function __construct() {}function __destruct() {}
}class Object extends Base {
function __construct() {parent::__construct();
}function __destruct() {
parent::__destruct();}
}$obj = new Object();unset($obj);?>
Constructors and Destructors
Marcus Börger PHP5 9
Properties can have default valuesBound to the class not to the objectDefault values cannot be changed but overwritten
<?php
class Object {var $prop = "Hello\n";
}
$obj1 = new Object;$obj1->prop = "Hello World\n";
$obj2 = new Object;echo $obj2->prop; // Hello
?>
Default property values
Class Object$prop/default
$obj2
Instance 2$prop
$obj1
Instance 1$prop
Marcus Börger PHP5 10
Static methods and propertiesBound to the class not to the objectCan be initialized
<?phpclass Object {var $pop;static $stat = "Hello\n";static function test() {echo self::$stat;
} }Object::test();$obj1 = new Object;$obj2 = new Object;?>
Static members
Class Object$stat
$obj2
Instance 2$prop
$obj1
Instance 1$prop
Marcus Börger PHP5 11
New pseudo constants__CLASS__ shows the current class name__METHOD__ shows class and method or functionSelf references the class itselfParent references the parent class$this references the object itself<?phpclass Base {
static function Show() {echo __FILE__.'('.__LINE__.'):'.__METHOD__."\n";
}}class Object extends Base {
static function Use() {Self::Show();Parent::Show();
} static function Show() {
echo __FILE__.'('.__LINE__.'):'.__METHOD__."\n";}
}?>
Marcus Börger PHP5 12
Controlling member visibility / Information hidingA derived class does not know inherited privatesAn inherited protected member can be made public
<?phpclass Base {public $a;protected $b;private $c;
}class Derived extends Base {public $a;public $b;private $c;
}?>
Visibility
Base$a$b$c
Derived
$a$b$cBase::$c
Marcus Börger PHP5 13
Constructor visibility
A protected constructor prevents instantiation
<?phpclass Base {
protected function __construct() {}
}class Derived extends Base {
// constructor is still protectedstatic function getBase() {
return new Base; // Factory pattern}
}class Three extends Derived {
public function __construct() {}
}?>
Marcus Börger PHP5 14
Clone visibility
A protected __clone prevents external cloning
<?phpclass Base {
protected function __clone($that) {}
}class Derived extends Base {
public function __clone($that) {return new Base;
}public static function copyBase($that) {
return Base::__clone($that);}
}?>
A protected __clone prevents external cloningA private final __clone prevents cloning
<?phpclass Base {
private final function __clone($that) {}
}class Derived extends Base {
// public function __clone($that) {// return new Base; // }// public static function copyBase($that) {// return Base::__clone($that);// }
}?>
Marcus Börger PHP5 15
ConstantsConstants are read only static propertiesConstants are always public
<?phpclass Base {const greeting = "Hello\n";
}class Dervied extends Base {const greeting = "Hello World\n";static function func() {
echo parent::greeting; }
}echo Base::greeting;echo Derived::greeting;Derived::func();?>
Marcus Börger PHP5 16
Abstract members
Properties cannot be made abstractMethods can be abstract
They don’t have a bodyA class with an abstract method must be abstract
Classes can be made abstractThe class cannot be instantiated
<?phpabstract class Base {abstract function no_body();
}
class Derived extends Base {function no_body() { echo "Body\n"; }
}
?>
Marcus Börger PHP5 17
Final members
Methods can be made finalThey cannot be overwrittenThey are class invariants
Classes can be made finalThey cannot be inherited
<?phpclass Base {final function invariant() { echo "Hello\n"; }
}class Derived extends Base {}final class Leaf extends Derived {}?>
Marcus Börger PHP5 18
Interfaces describe an abstract class protocolClasses may inherit multiple Interfaces
<?phpinterface Drawable {function draw();
}class Line implements Drawable {function draw() {};}class Rect implements Drawable {function draw() {};}class Circle implements Drawable {function draw() {};}class Ellipse extends Circle {function draw() {};}?>
Interfaces
Drawable
RectLine Circle
Rect
Marcus Börger PHP5 19
Property types
Declared propertiesMay have a default valueCan have selected visibility
Implicit public propertiesDeclared by simply using them in ANY method
Virtual propertiesHandled by interceptor methods
Static properties
Marcus Börger PHP5 20
Object to String conversion
__toString(): automatic object string conversion
<?phpclass Object {
function __toString() {return 'Object as string';
}}
$o = new Object;
echo $o;
$str = (string) $o;?>
Marcus Börger PHP5 21
Interceptors
Allow to dynamically handle non class membersLazy initialization of propertiesSimulating Object aggregation, Multiple inheritance
<?phpclass Object {
protected $virtual;function __get($name) {
return @$virtual[$name];}function __set($name, $value) {
$virtual[$name] = $value;}function __call($func, $params) {
echo 'Could not call ' . __CLASS__ . '::' . $func . "\n";}
}?>
Marcus Börger PHP5 22
Exceptions
Respect these rules1. Exceptions are exceptions2. Never use exceptions for control flow3. Never ever use exceptions for parameter passing
<?phptry {
// your codethrow new Exception();
}catch (Exception $e) {
// exception handling}?>
Marcus Börger PHP5 23
Exception specialization
Exceptions should be specialized
<?phpclass YourException extends Exception {}try {
// your codethrow new YourException();
}catch (YourException $e) {
// exception handling}catch (Exception $e) {
// exception handling}?>
Marcus Börger PHP5 24
Exception specialization
Exception blocks can be nestedExceptions can be rethrown<?phpclass YourException extends Exception { }try {
try {// your codethrow new YourException();
}catch (YourException $e) {
// exception handlingthrow $e;
}catch (Exception $e) {
// exception handling}
}catch (YourException $e) {
// exception handling}?>
Marcus Börger PHP5 25
Constructor failure
Constructors do not return the created objectExceptions allow to handle failed constructors
<?phpclass Object {
function __construct() {throw new Exception;
}}try {
$o = new Object;}catch (exception $e) {
echo "Object could not be instantiated\n";}?>
Marcus Börger PHP5 26
Reflection API
Can reflect nearly all aspects of your PHP codeFunctionsClasses, Methods, PropertiesExtensions
<?phpclass Foo {
public $prop;function Func($name) {
echo "Hello $name";}
}
reflection_class::export('Foo');reflection_object::export(new Foo);reflection_method::export('Foo', 'func');reflection_property::export('Foo', 'prop');reflection_extension::export('standard');?>
Marcus Börger PHP5 27
Iterators
Some objects can be iteratedOthers show their properties
<?php
class Object {public $prop1 = "Hello";public $prop2 = "World\n";
}
foreach(new Object as $prop) {echo $prop;
}
?>
Marcus Börger PHP5 28
<?phpclass Filter implements Iterator {
function __construct(Iterator $input)...function rewind()...function accept($value)...function hasMore()...function current()...function key()...function next()...
}?>
IteratorsInternal IteratorsUser Iterators
<?php$it = get_resource();foreach($it as $key=>$val) {// access data
}?>
<?phpinterface Iterator {
function rewind();function hasMore();function current();function key();function next();
}?>
<?php$it = get_resource();foreach(new Filter($it, $filter_param) as $key=>$val) {// access filtered data only
}?>
<?php$it = get_resource();for ($it->rewind(); $it->hasMore(); $it->next()) {
$value = $it->current(); $key = $it->key();}?>
Marcus Börger PHP5 29
PHP & UMLTraversable
Aggregate
+ getIterator () : Iterator
Iterator
+++++
rewind ()hasMore ()current ()key ()next ()
: void: boolean: mixed: mixed: void
Filter
+++++++
<<Implement>><<Implement>><<Implement>><<Implement>><<Implement>>
rewind ()hasMore ()current ()key ()next ()__construct (Iterator data)accept (mixed Value)
: void: boolean: mixed: mixed: void: void: boolean
IteratorImpl
+++++
<<Implement>><<Implement>><<Implement>><<Implement>><<Implement>>
rewind ()hasMore ()current ()key ()next ()
: void: boolean: mixed: mixed: void
Marcus Börger PHP5 30
PHP & UML
Marcus Börger PHP5 31
PHP & UML
Marcus Börger PHP5 32
Typehinting
PHP 5 allows to easily force a type of a parameterBeta 1 and beta 2 allow NULL with typehintsBeta 3 will have a syntax to decide about NULL
<?phpclass Object {
public function compare(Object $other) {// Some code here
}}?>
Marcus Börger PHP5 33
New extensions
New extensionsFFIDOMMySQLiPDOPIMPSimpleXMLSPLSQLiteXML + XSL