Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP dynamic class loading

Tags:

php

class

Lets say that I have an array that I want to convert to a value object.

My value object class is as follows:

/* file UserVO.php*/
 class UserVO
 {
    public $id;
    public $email;

     public function __construct($data)
     {
         $this->id = (int)$data['id'];
         $this->email = $data['email'];
     } 
 }

And I create my array of value objects as follows:

/* file UserService.php*/
$array = array(
array(...),
array(...));
$count = count($array);
for ($i = 0; $i < $count; $i++)
{
   $result[] = new UserVO($array[$i]);
}
return $result;

OK, so this all works fine. However, I'd like to specificy the VO that is to be created dynamically, so that I can have a single dynamic function to create my VO's.

Something like:

$ret = create_vo($array, 'UserVO');

function create_vo($data, $vo)
{
  $count = count($data);
  for ($i = 0; $i < $count; $i++)
  {
     $result[] = new $vo($data[$i]); //this obviously wont work...Class name must be a valid object or a string
  }
  return $result;
}

I realise that I could do this with a switch statement (iterating through all my VO's)...but there is no doubt a much much more elegant solution. It would also be supercool if I could lazy load the VO's as needed, instead of having multiple 'includes'

Any help much appreciated.

like image 390
JonoB Avatar asked Sep 10 '10 15:09

JonoB


2 Answers

$result[] = new $vo($data[$i]); //this obviously wont work...Class name must be a valid object or a string

Have you tried it? It works just as expected (in php 5.1, I don't know how was it with OOP in php 4, but if you are using __construct for constructor this should work).

To avoid multiple includes define magic function __autoload before using any class

function __autoload($className)
{
    require_once 'myclasses/'.$className.'.php';
}

So first call new UserVo will trigger this function to include file myclasses/UserVo.php.

like image 109
dev-null-dweller Avatar answered Oct 31 '22 21:10

dev-null-dweller


It appears that include_once()'s and require_once()'s performance is pretty bad.

My suggestion:

Kill all "require_once" and "include_once" and create an autoloader. Register this implementation

like image 1
Macsen Liviu Avatar answered Oct 31 '22 20:10

Macsen Liviu