note 52849 added to language.oop5.patterns
| From: | dmnEe0 at gmail dot com | Date: | Sat, 14 May 2005 21:13:27 +0000 |
| Subject: | note 52849 added to language.oop5.patterns | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-89436@lists.php.net to get a copy of this message | ||
I struggled a few hours on writing a simple Generic factory method for dynamic object factoring. I
initially went for call_user_func_array() to create the object but that obviously didn't work.
An anonymous function was what I needed. Here's the result (PHP5):
<?php
/**
* Name: Factory
* Author: Ezku
* Contact: dmnEe0 at gmail dot com
*/
class Factory
{
/**
* Generic factory method
* @param string Path to class definition
* @param string Basic class name
* @param string Derived class name
* @param array Class constructor arguments, optional
*/
public static function Generic($filename, $base, $derived, $args = array())
{
/**
* Check that the file exists
*/
if(file_exists($filename))
{
include_once $filename;
/**
* Check that the file contained the appropriate class definition
*/
if(class_exists($derived))
{
/**
* Create argument list for constructor
*/
$arglist = array();
for($i = 0, $n = count($args); $i < $n; $i++)
$arglist[] = '$args['.$i.']';
$arglist = implode(',',$arglist);
/**
* Create new instance via an anonymous function
*/
$new_class = create_function('$name, $args', 'return new
$name('.$arglist.');');
return $new_class($derived, $args);
}
else
throw new Exception("Definition file ($filename) did not contain definition for the $base
class <code>$derived</code>");
}
else
throw new Exception("Definition file ($filename) for the $base class
<code>$derived</code> was not found");
}
}
/**
* Useless usage example:
*/
function createCat($name, $scary_eyes = FALSE, $whiskers = TRUE)
{
$path = PATH_ANIMALS.'/'.$name.'.php';
$base = 'Cat';
$derived = $name.$base;
$args = array($scary_eyes, $whiskers);
return Factory::Generic($path, $base, $derived, $args);
}
// Create a MeowCat with scary eyes and whiskers
$cat = createCat('Meow', TRUE);
// Do whatever
?>
----
Manual Page -- http://www.php.net/manual/en/language.oop5.patterns.php
Edit -- http://master.php.net/manage/user-notes.php?action=edit+52849
Delete: added to the manual -- http://master.php.net/manage/user-notes.php?action=delete+52849&report=yes&reason=added+to+the+manual
Delete: bad code -- http://master.php.net/manage/user-notes.php?action=delete+52849&report=yes&reason=bad+code
Delete: spam -- http://master.php.net/manage/user-notes.php?action=delete+52849&report=yes&reason=spam
Delete: useless -- http://master.php.net/manage/user-notes.php?action=delete+52849&report=yes&reason=useless
Delete: other reasons -- http://master.php.net/manage/user-notes.php?action=delete+52849&report=yes
Reject -- http://master.php.net/manage/user-notes.php?action=reject+52849&report=yes
Search -- http://master.php.net/manage/user-notes.php