PDO在课堂上的良好实践和指导

时间:2012-11-14 08:49:56

标签: php class pdo

所有我一直在努力争取一两个星期试图绕过整个PDO,单身或不MVC和更多的东西。我现在已经编码了3个月,我想知道我是否最终做到了这一点。

我正在为班级等建立一个简单的学校应用程序......并且已经创建了一个名为sections的类,我现在已经将PDO合并到了。到目前为止,它的工作和功能都像id一样,但在我以相同的方式制作更多课程之前,我想知道是否有任何错误以及我如何改进。虽然我写了其他所有内容,但我自己并没有对数据库类本身。

class pdoDB {

/*** Declare instance ***/
private static $db = NULL;

/**
*
* the constructor is set to private so
* so nobody can create a new instance using new
*
*/
private function __construct() {
/*** maybe set the db name here later ***/
}

/**
*
* Return DB instance or create intitial connection
*
* @return object (PDO)
*
* @access public
*
*/
public static function getInstance() {

 if (!self::$db)
{
self::$db = new PDO('mysql:host=localhost;dbname=attendance_ksu','root','root');;
self::$db-> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
return self::$db;
}

/**
*
* Like the constructor, we make __clone private
* so nobody can clone the instance
*
*/
private function __clone(){
}

} /*** end of class ***/

现在我的部门上课。

class Section  {


// if protected can't loop through on html page into table
    // I don't want to make getter method for each attribute.
    // all data will be coming from the db

public $id;
public $section_number;
public $subject;
public $classroom;
public $level_id;
public $shift;
public $course;
public $campus;
public $times;
public $academic_year;
public $start_date;
public $end_date;
public $max_st_number;
public $status;

// retrieve all sections in db

public static function get_all_sections() {

try {

    // maybe a waste of time doing this bit?? not sure!! the " if(!isset($db)) "

if(!isset($db)) {
$db = pdoDB::getInstance();

/*** echo a message saying we have connected for testing reasons only ***/
echo 'Connected to database <br />';
}

/*** The SQL SELECT statement ***/
$sql = "SELECT * FROM sections";
$stmt = $db->query($sql);
$objs = $stmt->fetchALL(PDO::FETCH_CLASS, 'Section');

// 1. return the complete array of data so I can loop through it later

return $objs;  

// 2. Or echo out a loop immediately where this method is called

   /*

foreach ($objs as $section) {
echo "Section:" . $section->section_number . " | " . 
     "Subject: {$section->subject}" . "<br/>";
}

    */

$db = null;   
    }

catch(PDOException $e)
{
echo $e->getMessage();
}

}


// Get the section details by id from db
// will be passed via the URL as $_GET

public static function get_section_by_id($id) {

try {

if(!isset($db)) {
$db = pdoDB::getInstance();

/*** echo a message saying we have connected ***/
echo 'Connected to database<br />';
}   
     /*** prepare the SQL statement ***/
$stmt = $db->prepare("SELECT * FROM sections WHERE id = :id");

/*** bind the paramaters ***/
$stmt->bindParam(':id', $id, PDO::PARAM_INT);

/*** execute the prepared statement ***/
$stmt->execute();

/*** fetch the results and give it a class ***/
$section = $stmt->fetchObject('section');
return $section;

$db = null;   
    }

catch(PDOException $e)
{
echo $e->getMessage();
}   

}
}

我只是在页面上调用get_all_sections()方法并将结果循环到表中。其他页面也将在此方法中完成。没有将我的学习曲线扩展到MVC等......这是一种可接受的方法,我是朝着正确的方向前进吗?

EG:

<?php
// some code
$sections = Section::get_all_sections();

// any other necessary code
?>

<html> 
<body>

    <table class="table table-striped table-bordered table-highlight" id="example">
<thead>
<tr>
<th>#</th>
<th>Section Number</th>
<th>Subject</th>
<th>Course</th>
<th>Students</th>
<th>Level</th>
<th>Campus</th>
<th>Classroom</th>
<th>Shift</th>
<th>Start date</th>
<th>End date</th>
<th>Teacher</th>
<th>&nbsp;</th>
</tr>
</thead>

<tbody>
<?php 
$key =  1;
foreach($sections as $section) {
?>
<tr>
<td><? echo $key++ ?></td>
<td><a href=""><?php echo $section->section_number ?></a> </td>
<td><?php echo $section->subject ?> </td>
<td><?php echo $section->course ?> </td>
<td><?php echo $section->no_students ?> sts</td>
<td><?php echo $section->level_id ?> </td>
<td><?php echo $section->campus ?> </td>
<td> <?php echo $section->classroom ?></td>
<td><?php echo $section->shift ?> </td>
<td><?php echo date("d-M-Y",strtotime($section->start_date ))?></td>
<td><?php echo date("d-M-Y",strtotime($section->end_date ))?></td>
<td>

<?php 
if($section->username  =="")
{
echo "<a href=\"add_section_teacher.php?id=".urlencode($section->id )."&section_number=".urlencode($section->section_number )."\">Not assigned</a>";

} else {
echo "<a href=\"edit_section_teacher.php?ts_id=".urlencode($section->ts_id )."\">";
echo $section->username ; 
echo "</a>";
}       
?>  
</td>
<td><a href="delete.php?id=<?php echo $section->id ; ?>" 
onclick="return confirm('Are you sure you want to delete section <?php echo $section->section_number ; ?> ?');">Delete</a></td>
</tr>
<? }?></tbody>
</table>

提前感谢任何反馈和建议。我想要正确地学习这个,所以任何详细的feedabck都会受到赞赏,因为这里的目标是学习。

2 个答案:

答案 0 :(得分:0)

我认为你的PDO工厂还可以。 您的课程部分不合适,因为它不尊重单一责任原则。

如果需要,部分应该只是一个具有属性,getter和setter的类以及一些计算方法。没有指向数据库的链接。您应该使用Repository模式来放置bdd访问方法,例如find,findAll ...

然后你应该在控制器中调用你的存储库。

class SectionRepository{
    public function findAll(){
       $db = pdoDB::getInstance();
       $result = $bd->query(SELECT * FROM sections);
       return $result->fetchAll(PDO::FETCH_CLASS,Section);  
    }
}

关于您正在使用的PDO Factory:

class PDOFactory{
    private static $connection = null;
    public static function getConnection(){
        if(self::$connection === null){
             self::$connection = new PDO();//here you can use a config file if you want
             self::$connection -> setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
        }
        return self::$connection;
}

它不是一个真正的单例,因为不存在私有构造(在php中不可能重载)并且因为PDOFactory不扩展PDO但行为完全相同。

答案 1 :(得分:0)

尽管Artragis的上述答案确实是走的路(长期),但我觉得OP的痛苦在整个OOP之谜中挣扎着他的思绪 - 我现在一直在努力争取和过去两年没有真正到达任何地方。

我对他简单的分类的观察:

  • 单身模式没问题
  • 单身人士的用法不合适: 单身本身旨在被实例化&#39; (可能错了 只选择一次,然后保持开放,只要它是 需要的。

我建议您执行以下操作:

  • 删除测试以检查$ db是否设置 - 单例只创建一个连接(如果尚未存在)
  • 删除$ db变量的取消设置 - 只需将连接保持打开状态,直到垃圾收集通过
  • 一个可选步骤是将$ db_handle注入Section-class(通过构造函数最容易) - 这会使你的Section-class只与pdoDB-class松散耦合(好吧,好吧 - 也许你需要一个由pdoDB-class首先实现的中间接口,但你明白了这一点,并且更容易测试