473,834 Members | 2,181 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

HACK : Mixin in PHP5

Hello !

If somebody is interested, here is a small hack I've done today.

There are still some curious effects, but I'm pretty satisfied by the
results, since PHP is not very flexible.

Let me know what you think, I'm looking into talking about somethin ;)
Cheers,
zimba

---------
<?php
/*
* AUTHOR : Created on 5 janv. 2005 by Jonas Pfenniger
* LICENSE : You are free to use this code
* DESC : Mixins are pretty similar to multiple inheritance. The
goal is to
* add capabilites from a class to another class or instance.
* I don't know what it's usefull for, but I'm sure you'll find out ;)
* Because of the limitations of the PHP language, I was not able to do
some
* things, but it was fun to find workarouds where it's possible..
*
* This hack was inspired by the Ruby language, who supports mixins
natively
* See: http://www.ruby-lang.org and http://www.rubyonrails.com
*
*/

/**
* Mixin : allow to inheritate methods and properties of multiple
objects
* - Limitations :
* - Cannot inherit __get and __set
* - Reflection does not show the new methods
* - Some behaviors are still weird
*/
class Object
{
/**
* Contains class_name => instances
*/
private $mixin_objects = array();

/**
* Contains method_name => calling code
*/
private $mixin_methods = array();

/**
* For the tests
*/
public $hoi = 0;

/**
* Method and variable mixing
* @var string A class name
*/
public function mixin($class_na me)
{
if (!class_exists( $class_name))
trigger_error(" Class name $class_name is not loaded", E_USER_ERROR);
if (array_key_exis ts($class_name, $this->mixin_objects) )
{
trigger_error(" Mixin $class_name allready registered");
return;
}

// Variable argsnum on constructor
$args = func_get_args() ;
$c = 'return new '.$class_name.' (';
for($i=1; $i<count($args) ; $i++)
{
$c .= '$args['.$i.']';
if ($i < count($args) - 1) $c .= ',';
}
$c .= ');';

// Create instance
$x = eval($c);
if ($x instanceof MixinChild)
{
$x->setMixinParent ($this);
}
$this->mixin_object s[$class_name] = $x;

// Link methods
$refl_class = new ReflectionClass ($class_name);
$refl_methods = $refl_class->getMethods() ;
foreach($refl_m ethods as $refl_method)
{
// TODO : Inherited methods should not be added

// Do not private and protected methods
if ($refl_method->isPublic())
$this->mixin_method s[$refl_method->getName()] =
'$this->mixin_object s['.
$class_name .
']->'. $refl_method->getName();
}

// Link parameters
foreach ($x as $k => &$v)
{
if (!isset($this->$k))
$this->$k = &$v;
}
}

/**
* Method overloading
* @var string Method name
* @var array Method arguments
*/
public function __call($method_ name, $args)
{
if (!array_key_exi sts($method_nam e, $this->mixin_methods) )
{
trigger_error(" Method $method_name does not exist");
return;
}

$c = 'return '. $this->mixin_method s[$method_name] .'($args[0]';
for($i=1; $i<count($args) ; $i++) $c .= ',$args['.$i.']';
$c .= ');';

return eval($c);
}

public function hasMixin($class _name)
{
return array_key_exist s($class_name, $this->mixin_objects) ;
}

/**
* For the tests
*/
public function directCall()
{
return;
}
}

/**
* Use this class if you want the mixed class to have access to the
parent
*/
abstract class MixinChild extends Object
{
protected $mixin_parent = null;

public function setMixinParent( Object $mixin_parent)
{
$this->mixin_parent = $mixin_parent;
}

}

/**
* Implementation example
*/
class Prout extends MixinChild
{
public $woot = 2;

public function __construct($wo ot)
{
$this->woot = $woot;
}

/**
* Woot is so cool
*/
public function Woot($a, $b, $c)
{
return "$a, $b and $c are reading /.";
}

public function get()
{
return $this->woot;
}

public function set($x)
{
$this->woot = $x;
$this->mixin_parent->hoi = $x;

}

public function indirectCall()
{
return;
}

public function __set($k, $v)
{
$this->mixin_parent->$k = "PHP";
}

public function __get($k)
{
return "I love ".$this->mixin_parent->$k;
}
}

/***\
|***|==> Start demo code HEHE
\***/

define('BR', "<br />\n");
echo "<h3>Mixin demo</h3>";
$x = new Object();

// Constructor assignation
$x->mixin('Prout ', 6);
echo "Constructo r test : ". ($x->woot==6?'true' :'false'), BR;

// Settest
$x->set(5);
echo "Set test: " . ($x->woot==5?'true' :'false'), BR;
echo "Set parent test: " . ($x->hoi==5?'true': 'false'), BR;

// Gettest
$x->woot = 3;
echo "Get test: ". ($x->get()==3?'true ':'false'), BR;

// Call test
echo "Method call test: " . $x->Woot('nitro' , 'tritoul', 'zimba'), BR;
// __get and __set test
$x->notAssignedV ar = 3;
echo "__set and __get test : " . ($x->notAssignedV ar == 'I love
PHP'?'true':'fa lse'), BR;

//********** BENCHMARKS ***********

$loops = 10000;

// Direct call
$start_time = (float) array_sum(explo de(' ', microtime()));
for($i=0; $i<$loops; $i++)
{
$x->directCall() ;
}
$end_time = (float) array_sum(explo de(' ', microtime()));
$direct_time = $end_time - $start_time;
echo "Direct call bench($loops) : ". $direct_time, BR;

// Mixin call
$start_time = (float) array_sum(explo de(' ', microtime()));
for($i=0; $i<$loops; $i++)
{
$x->indirectCall() ;
}
$end_time = (float) array_sum(explo de(' ', microtime()));
$mixin_time = $end_time - $start_time;
echo "Mixin call bench($loops) : " . $mixin_time, BR;

// Difference
echo "Execution time difference : ".$mixin_ti me / $direct_time, BR;
echo "<b>the end</b>", BR;
echo "<pre>";
print_r($x);
echo "</pre>";

?>

Jul 17 '05 #1
0 1626

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
2740
by: Udo Gleich | last post by:
Hi, I try to implement mixin classes. Thats why I need to make a new class at runtime. --tmp.py------------------------------------- import new class K1(object):
0
1334
by: Paolino | last post by:
I had always been negative on the boldeness of python on insisting that unbound methods should have been applied only to its im_class instances. Anyway this time I mixed in rightly, so I post this for comments. ###### looking for a discovery .Start ################# class _Mixin(object): def __init__(self,main,instance,*args,**kwargs): # do mixin businnes main.__reinit__(self,instance) # the caveated interface
0
345
by: barnesc | last post by:
>So mixins are just a sub-class of sub-classing? > >I've just found this: > > >A mixin class is a parent class that is inherited from - but not as >a means of specialization. Typically, the mixin will export services to a >child class, but no semantics will be implied about the child "being a >kind of" the parent. >
6
2490
by: Alex Hunsley | last post by:
I know that I can catch access to unknown attributes with code something like the following: class example: def __getattr__(self, name): if name == 'age': return __age else: raise AttributeError
3
1482
by: Ed Leafe | last post by:
In Dabo, we create cursor classes that combine the backend-specific dbapi cursor class with our own mixin class that adds framework- specific behaviors. This has been working well for a couple of years now with many different backends, but today I'm getting errors with our Firebird class. I've checked the kinterbasdb site, and found nothing there that was helpful. The error reads: TypeError: Error when calling the metaclass bases type...
2
2211
by: ish | last post by:
I think this is more of a style question than anything else... I'm doing a C++ wrapper around a C event library I have and one of the items is a timer class, I'm also using this task to learn C++. Is it cleaner to have users subclass my Timer class and implement the on_timeout() method? Or should the user use a mixin and provide the mixin to my Timer class? The subclass method kinda looks like this..
1
1508
by: Scott David Daniels | last post by:
Here is a Mix-in class I just built for testing. It is quite simple, but illustrates how Mixins can be used. class Pending(object): _pending = iter(()) def __new__(class_, *args, **kwargs): try: return class_._pending.next() except StopIteration:
19
2374
by: McKirahan | last post by:
I am working in two environments neither configuration of which I can change; one's my Web host the other a client. My Web host requires the use of the ".php5" extension to use PHP v5.1.4; where ".php" is used for PHP v4.3.11. My client supports PHP v5.2.0 with the ".php" extension. Is there a way to reliably determine if the ".php5" extension must be used on a server? Perhaps via a "phpinfo()" value?
1
1434
by: Ole Nielsby | last post by:
Given these 3 classes class A {virtual void a(){}}; class B {virtual void b(){}}; class C: public A, public B {}; I want the offset of B in C, as a size_t value, and preferably as a constant expression. I got a solution that seems to work on VC9Express:
0
9643
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
1
10544
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10214
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7754
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6951
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5790
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4425
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3973
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3079
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.