我刚刚接触过PHP,我无法理解为什么下面的代码不起作用。 如果我使用相同的代码而不使用类,那么工作就可以了。
<?php
class DAL
{
public $Conn;
public function __construct()
{
global $Conn;
$Conn = new PDO("mysql:host=localhost;dbname=football", "root","");
$Conn->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ);
}
}
class BLL
{
public function GetSeason()
{
$conn = new DAL();
$result = $conn->Conn->query("Select * from season");
print_r($result->fetchAll());
}
}
?>
答案 0 :(得分:1)
如果我理解正确,DAL为Data access layer,BLL为Business logic layer。
两者通常不是由一个类或对象表示,而是包含表示应用程序中不同抽象级别的对象。
数据访问层由Data access objects组成,业务逻辑层由Business Objects组成。因此,每个业务对象应该有一个数据访问对象。通常,数据访问对象应该共享一个接口(即应该扩展相同的数据访问对象抽象类):
abstract class DataAccessObject
{
protected $conn;
public function __construct($conn)
{
$this->conn = $conn;
}
abstract public function all();
abstract public function get($id);
abstract public function save($object);
abstract public function delete($object);
}
因此,使用您的示例,代码可能如下所示。这是你的季节DAO:
final class SeasonDataAccessObject extends DataAccessObject
{
public function all()
{
$query = $this->conn->query('SELECT * FROM `season`');
$seasons = [];
foreach ($query->fetchAll() as $result) {
$seasons[] = $this->hydrate(new Season, $result);
}
return $seasons;
}
public function get($id)
{
// Execute select statement and hydrate result into
// Season Business Object.
// Should return instancs of Season.
}
public function save($season)
{
return null === $season->id
? $this->insert($season)
: $this->update($season);
}
public function delete($season)
{
// Execute delete statement.
}
private function hydrate(Season $season, $result)
{
// Fill $season attributes with values from $result.
}
private function update(Season $season)
{
// Execute update statement.
}
private function insert(Season $season) {
// Execute insert statement.
}
}
这是你的季节业务对象:
abstract class BusinessObject
{
private $id;
public function setId($id)
{
$this->id = $id;
return $this;
}
public function getId()
{
return $this->id;
}
}
final class Season extends BusinessObject
{
// Some properties of Season and setters and getters for them.
}
最后,你可以在你的程序中使用它:
$conn = new PDO('mysql:host=localhost;dbname=football', 'root', '');
$conn->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ);
$seasonDAO = new SeasonDataAccessObject($conn);
$seasons = $seasonDAO->all();
print_r($seasons);
我猜你从"Microsoft Application Architecture Guide"或微软世界的其他地方获得了这个术语(你的属性命名也代表它:))。在现代世界中,我猜数据访问对象是Repository,而Business对象是实体。
这是非常高级的东西,甚至不涉及OOP,而是Object-oriented design。因此,您必须首先了解OOP,因为正如评论中提到的那样,现在您的代码是程序性的。在类中包装代码并不能使代码面向对象(在一天结束时,这是面向对象的编程,而不是面向类的编程;)
所以,请从PHP的OOP主题(即this one)开始,逐渐你会在这方面做得更好。
答案 1 :(得分:-1)
完成!!!!!
非常感谢你们!
class DAL
{
public $Conn;
public function __construct()
{
$this->Conn = new PDO("mysql:host=localhost;dbname=football",
"root","");
$this->Conn->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ);
}
}
class BLL
{
public function GetSeason()
{
$conn = new DAL();
$result = $conn->Conn->query("Select * from season");
print_r($result->fetchAll());
}
}