我最近使用数据库对象超类做了一些项目,我用它来快速一次性记录查询/更新,并使用适当的类(如User类)进行扩展.
我发现我写的很多类都有完全相同的方法:query_values(),update(),delete()等.
public function __construct($table, $db_object, $record_id = null){
$this->db = $db_object; // Database object with query methods
$this->table = $table; // The name of the database table
$this->get_column_data();
if(!is_null($record_id)){
// This retrieves all column values,
// stores into private $fields array property
$this->query_values($record_id);
}
}
子类构造函数如下所示:
public function __construct($db_object, $record_id = null){
parent::__construct($this->table, $db_object, $record_id);
}
在$top属性的顶部定义,因为我们应该知道这个特定对象使用哪个表.
现在,所有常见的记录管理方法都在一个地方,并且特定于该类的方法都是在它们各自的子类中定义的.
我在这里看到的最大缺点是所有数据字段都被拉出并封装在$fields属性中,因此需要定义泛型get和set方法(我通常这样做)几乎否定封装*,或者方法必须为我们想要公开的每个属性专门定义.
*例:
$user_id = $User-> id; //不使用我的方法
与
$user_id = $User-> _get(‘id’); //访问$User-> fields [‘id’]
你认为这是一个缺点,还是一个加分?目标是易于使用,面向对象(封装),并且只是非常棒!
解决方法:
好吧,你可以让你的生活轻松,并使用PHP的神奇重载__call方法来创建通用的getter和setter.您可以将以下方法添加到“数据库对象超类”:
/**
* Create magic getter and setter methods to access private $fields array
*/
public function __call($method, $args)
{
$prefix = substr($method, 0, 3);
$prop = lcfirst(substr($method, 3));
if (isset($this->fields[$prop])) {
if ($prefix == 'get') {
return $this->fields[$prop];
} elseif ($prefix == 'set') {
if ( ! isset($args[0])) {
$msg = 'Missing argument: ' . get_class($this) . "::$method must specify a value";
throw new invalidargumentexception($msg);
}
$this->fields[$prop] = $args[0];
return;
}
}
$msg = 'Invalid method: ' . get_class($this) . "::$method does not exist";
throw new BadMethodCallException($msg);
}
那么让我解释一下这里发生了什么. magic __call方法将接收对任何与对象的具体方法之一不匹配的对象方法的调用.它接收作为参数的被调用方法的名称及其参数数组.
上面的__call方法进行快速子检查以查看该方法是“getter”还是“setter”(使用方法名称的前三个字母).它期望$fields数组存储小写的“属性”名称(lcfirst),并使用setter / getter前缀之后的所有内容作为预期的属性名称.
如果属性与getter方法匹配,则返回该属性.如果不是,则抛出SplException BadMethodCallException.这是最佳实践,因为在PHP中包含Spl异常.
同样,如果没有指定参数,setter方法也会抛出SplException invalidargumentexception.
PHP的神奇方法将改变你的生活.您也可以使用__get和__set以类似的方式分配$fields数组值,而无需进行虚假方法调用.兴奋起来 :)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。