我只想知道我是否在正确的道路上。由于数据几乎相同,因此使大部分功能抽象化似乎并不必要。这是一种无效的方法吗?PHP摘要;这是使用抽象类的正确方法吗?
<?php
abstract class Model_Tasks {
/**
* Database object
*
* @access protected
*/
protected $db;
/**
* User ID
*
* @access protected
*/
protected $uid;
/**
* Data array
*
* @access protected
*/
protected $data;
/**
* SQL Query
*
* @access protected
*/
protected $query;
/**
* __construct
*
* @access protected
*/
protected function __construct($query) {
$this->db = Model_DB::getInstance();
$this->uid = $_SESSION['uid'];
$this->query = $query;
$this->getTasks();
}
/**
* getTasks
*
* @param string
* @access abstract protected
*/
protected function getTasks() {
$result = $this->db->prepare($this->query);
$result->execute(array(
':uid' => $this->uid
));
$this->data =& $result->fetchAll();
$this->taskCount = $result->rowCount();
}
/**
* constructTask
*
* Build the HTML of a task
*
* @param int
* @param int
* @param string
* @param string
* @access protected
*/
protected function constructTask(
$id, $cost, $title, $checked = 0
) {
$cost = money_format('$%i', $cost);
$title = stripslashes($title);
return '
<label class="task">
<input type="checkbox" name="done[]" rel="'.$id.'" '.($checked?'checked="checked"':'').' />
<code>'.$cost.'</code> — '.$title.'
</label>'."\n";
}
/**
* generateOutput
*
* Call by key [pending, completed] and return the constructed tasks
*
* @param bool
* @access final public
*/
final public function generateOutput($checked) {
try {
if(!is_bool($checked)) throw new Exception('generateOutput must contain a boolean variable');
if(!isset($this->data)) throw new Exception('Array has not been set.');
else $data = $this->data;
} catch(Exception $e) {
die('<pre>'.$e->getMessage().'<hr />'.$e->getTraceAsString());
}
if(is_array($data)): foreach($data AS &$r)
$str .= $this->constructTask($r['id'], $r['cost'], $r['title'], $checked);
else:
$str = '<label class="tasks"></label>';
endif;
return $str;
}
}
// ------------------------------------------------------------------------
/**
* pendingTasks
*
* @access public
*/
class pendingTasks extends Model_Tasks {
public $taskCount;
public function __construct() {
$query = '
SELECT id, title, cost
FROM tasks
WHERE (
status IS FALSE
AND uid = :uid
) ORDER BY cost DESC
';
parent::__construct($query);
}
}
/**
* completedTasks
*
* @access public
*/
class completedTasks extends Model_Tasks {
public function __construct() {
$query = '
SELECT id, title, cost
FROM tasks
WHERE (
status IS TRUE
AND uid = :uid
) ORDER BY id DESC
LIMIT 7
';
parent::__construct($query);
}
}
它所做的是打印任务与特定的查询,并返回一个关联数组。
如果你没有任何抽象方法,那么它真的是“抽象的”呢?您可以通过传递查询直接实例化“Model_Tasks”类... – landons 2012-01-17 04:27:45
Lol的确如此。不过,我只是想抓住这个概念。 – 2012-01-17 04:28:56
哦......我现在明白了。你声明构造函数是受保护的。这是使它变得抽象的一种奇怪的方式;) – landons 2012-01-17 04:36:42