我想使用依赖注入来指定数据对象类的表名和允许列。我的计划是做一些事情:
class DatabaseTable implements DatabaseTableInterface {
protected $_table_name;
protected $_columns;
public function __construct($table_name, $columns){
$this->_table_name = $table_name;
$this->_columns = $columns;
}
public function addColumn($new_column) {
...
}
public function getColumns() {
...
}
...
}
class UserObject implements UserObjectInterface {
protected $_table; // Should be a DatabaseTable object
public function __construct($table){
$this->_table = $table; // Inject a DatabaseTable object here
}
// Set the value of a particular property of this User
public function setValue($column, $value){
// Only allow if the column is present in the list of permissible columns in the DatabaseTable object
...
}
}
可以使用哪个,例如:
// Initial table parameters
$user_table = new DatabaseTable("user", ["id", "name", "email"]);
// Create a new user object
$user = new User($user_table);
addColumn
方法基本上为特定表的白名单添加了一列。多个数据对象类型可能需要访问同一个表,这就是我将其分解为一个单独的类的原因。此外,即使在实例化特定对象之后,也应该可以随时动态地将列添加到白名单中:
// This is OK
$user->setValue("name", "Alex");
// This is not OK (yet)
$user->setValue("marbles", 0);
// Add "marbles" column to the whitelist
$user_table->addColumn("marbles");
// Now it is OK!
$user->setValue("marbles", 0);
我知道在PHP5中,这将起作用,因为对象是由“引用”分配的。但是,我是否违反了任何设计原则,允许在将依赖注入其依赖后修改依赖?