我正在编写一个开发模块(所以请不要“你不应该这样做”的评论)。
我的框架已经使用了 __autoload(),所以我不能使用它。我也想避免使用 eval() 和编写临时文件。有没有办法即时创建子类?
比如,我可以使用 __call() 创建方法,使用 __get() / __set() 创建属性,但我更喜欢动态创建子类。就像,在使用“用户”表时,TableUsers 作为 Table 的子类,以确保类中的属性与表中的字段匹配。
对于这个实现,我将从一个有针对性的用法开始:
include "table.creator:///user_table/TableUsers/id";
$ut = new TableUsers();
注意这绝不应该用于生产代码,但它对原型设计很有用。
首先定义一个流包装器:
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;
}
}
}
然后在我们的代码中,我们必须像这样注册流包装器。
stream_register_wrapper("table.creator", "TableMaker_StreamWrapper");
然后,当您想围绕一个类创建表包装器时,您必须...
include("table.creator:///my_table/MyTableClass/id");
然后你就可以new MyTableClass
心满意足了。
如果你想要额外的语法糖,你可以创建一个像这样的小工厂函数。
function get_table($tableName, $className, $pk= "id"){
if (!class_exists($className)){
require("table.creator":///".$tableName."/".$className."/".$pk);
}
return new $className();
}
那你只能说。
$table = get_table("users", "UserTable");
希望这可以帮助