[TYPO3-dev] Extending classes on demand
Johannes Reichardt
typo3 at gramba.de
Tue Aug 29 14:39:20 CEST 2006
Hi Wolfgang,
thanx a lot!
That comment on the php reflection manual and the __autload function
seem to bring me much closer (i post it here because it sounds quite
interesting)
|If you've ever wanted to do dynamic class loading in PHP5, especially
when the class you're trying to dynamically load is a Singleton (and
therefore you cannot use the new operator), you can do something like
this example below, using the PHP5 Reflection API:
<?php
abstract class Shape
{
static public function makeShape( $shapeName )
{
$shapeInstance = null;
$shapeClass = new ReflectionClass( $shapeName );
$shapeMethod = $shapeClass->getMethod( 'getInstance' );
$shapeInstance = $shapeMethod->invoke( null );
$shapeClass = null;
$shapeMethod = null;
return $shapeInstance;
}
abstract public function doStuff();
}
class Triangle extends Shape
{
private static $instance = null;
private function __construct() { }
public static function getInstance()
{
if ( null == self::$instance )
{
self::$instance = new self;
}
return self::$instance;
}
public function doStuff() { }
}
$typeOfShape = 'Triangle';
$shape = null;
try
{
$shape = Shape::makeShape( $typeOfShape );
}
catch ( Exception $e )
{
print "Error creating shape '$typeOfShape'! " . $e->getMessage() . "\n";
}
if ( null != $shape )
{
// $shape will be an instance of Triangle
$shape->doStuff();
}
?>
So by changing the value of $typeOfShape you can dynamically load the
appropriate Shape subclass at runtime, thus facilitating a sort of
plug-in style architecture for your classes. You can just drop in new
Shape subclasses and not have to modify any of the Shape class code to
support them in its factory method makeShape() :-)
If your subclasses are all in separate files, you could even make the
'including' of these files dynamic as well, by adding these lines to the
Shape::makeShape() method after the $shapeInstance is initialized:
<?php
ini_set( 'include_path', ini_get( 'include_path' ) . PATH_SEPARATOR .
'/path/to/your/php/class/include/files' );
/**
* Assuming your subclasses are in files called 'class_$shapeName.php' :-)
* Of course doing a dynamic require() could be a security problem depending
* on how you validate/clean your $shapeName method parameter (if at all
;-))
*/
require_once( "class_$shapeName.php" );
?> |
> *hiya!*
>
> On Tue, 29 Aug 2006, Johannes Reichardt wrote the following:
>
>> thanx for the answer. Somehow classes in php still really confuse me and
>> i am far away from really understanding i think.
>>
>
> Take a look at
> http://www.php.net/manual/en/language.oop5.php (PHP 5)
> http://www.php.net/manual/en/language.oop.php (PHP 4)
>
>
> bye
> Wolfgang
>
> _______________________________________________
> TYPO3-dev mailing list
> TYPO3-dev at lists.netfielders.de
> http://lists.netfielders.de/cgi-bin/mailman/listinfo/typo3-dev
>
>
More information about the TYPO3-dev
mailing list