For this implementation I will start out with a targeted usage:
include "table.creator:///user_table/TableUsers/id";
$ut = new TableUsers();
NOTE This should NEVER be used for production code but it is useful for prototyping.
First off define a stream wrapper:
class TableMaker_StreamWrapper {
protected $_pos = 0;
protected $_data;
protected $_stat;
/**
* Opens the script file and converts markup.
*/
public function stream_open($path, $mode, $options, &$opened_path)
{
// break path into table name, class name and primary key
$parts = parse_url($path);
$dir = $parts["path"];
list($garbage, $tableName, $className, $primaryKey) = explode("/", $dir, 4);
$this->_data = '<?php class '.$className.' extends MyBaseClass {'.
' protected $primaryKey = "'.$primaryKey.'";'.
'}';
return true;
}
public function url_stat()
{
return $this->_stat;
}
public function stream_read($count)
{
$ret = substr($this->_data, $this->_pos, $count);
$this->_pos += strlen($ret);
return $ret;
}
public function stream_tell()
{
return $this->_pos;
}
public function stream_eof()
{
return $this->_pos >= strlen($this->_data);
}
public function stream_stat()
{
return $this->_stat;
}
public function stream_seek($offset, $whence)
{
switch ($whence) {
case SEEK_SET:
if ($offset < strlen($this->_data) && $offset >= 0) {
$this->_pos = $offset;
return true;
} else {
return false;
}
break;
case SEEK_CUR:
if ($offset >= 0) {
$this->_pos += $offset;
return true;
} else {
return false;
}
break;
case SEEK_END:
if (strlen($this->_data) + $offset >= 0) {
$this->_pos = strlen($this->_data) + $offset;
return true;
} else {
return false;
}
break;
default:
return false;
}
}
}
Then within our code we have to register the stream wrapper like so.
stream_register_wrapper("table.creator", "TableMaker_StreamWrapper");
Then when you want to create a table wrapper around a class you have but to ...
include("table.creator:///my_table/MyTableClass/id");
and then you will be able to make new MyTableClass
to your hearts content.
if you want additional syntactic sugar you can create a little factory function like this.
function get_table($tableName, $className, $pk= "id"){
if (!class_exists($className)){
require("table.creator":///".$tableName."/".$className."/".$pk);
}
return new $className();
}
Then you can just say.
$table = get_table("users", "UserTable");
Hope this helps