I have several static factory patterns in my PHP library. However, memory footprint is getting out of hand and we want to reduce the number of files required during execution time. Here is an example of where we are today:
require_once('Car.php');
require_once('Truck.php');
abstract class Auto
{
// ... some stuff ...
public static function Create($type)
{
switch ($type) {
case 'Truck':
return new Truck();
break;
case 'Car':
default:
return new Car();
break;
}
}
}
This is undesirable because Car.php AND Truck.php will need to be included even though only one or the other may be needed. As far as I know, require/include and their ..._once variation include libraries at the same scope as it's call. Is this true?
If so, I believe this would lead to a memory leak:
abstract class Auto
{
// ... some stuff ...
public static function Create($type)
{
switch ($type) {
case 'Truck':
require_once('Truck.php');
return new Truck();
break;
case 'Car':
default:
require_once('Car.php');
return new Car();
break;
}
}
}
It looks to me that in the 2nd example, multiple calls to Create() would lead to multiple requires because of the scope of the call even though the require_once flavor is used.
Is this true? What is the best way to include libraries dynamically in php in an example such as these?
Thanks!