契约式编程
使用抽象类和接口实现契约式编程,这样编程可以使结构更清晰,扩展性高;
特别适用于团队开发项目框架编写,比如可以通过定义一个数据库操作模型module,使所有需要操作数据库的module派生类都必须实现模型中的方法,这样就实现了数据层与控制层的分离,编写控制层只需要有数据层的文档即可知道基本操作;
如何使用抽象类?
抽象类定义基本方法,而具体的功能实现交给具体实现的类,当需要更换操作是,只需要重写抽象类中的基本方法
如何使用接口?
接口是用来约束一个类型,实现面向对象编程的多态性,我们定义了一个类型,而这个类型回派生很多类型,但是这些类型都需要有基类型的这些操作
例:
image.class.php
//定义一个图像接口
interface image{
//创建图像
public function getImage();
}
baseImage.class.php
include_once 'fileNotFoundException.class.php';
include_once 'image.class.php';
abstract class baseImage implements image{
protected $path; //图片路径
protected $info; //信息数组
public function __construct($path){
$this->path=$path;
if(!file_exists($this->path)){
throw new fileNotFoundException("文件 ".$path." 不存在" );
}
}
//生成信息
protected function createInfo(){
$this->info['size']= filesize ( $this->path );
$this->info['type']= filetype ( $this->path );
}
public function __get($k){
if($k=='info'){
$this->createInfo();
}
return $this->$k;
}
}
jpgImage.class.php
include_once 'image.class.php';
include_once 'baseImage.class.php';
class jpgImage extends baseImage implements image{
public function getImage(){
echo '创建一个 jpg 类型的图片';
}
}
PHP 的详细介绍:请点这里
PHP 的下载地址:请点这里