Fruit.php
- <?php
- /**
- * @author Gonn, http://www.nowamagic.net/
- */
- interface Fruit {
- public function showColor();
- }
- Apple.php
- class Apple implements Fruit {
- private $color;
- function getColor(){
- return $this->color;
- }
- function setColor($value){
- $this->color=$value;
- }
- function showColor(){
- echo "Apple Color:" . $this->color;
- }
- }
- Banana.php
- class Banana implements Fruit {
- private $color;
- function getColor(){
- return $this->color;
- }
- function setColor($value){
- $this->color=$value;
- }
- function showColor(){
- echo "Banana Color:" . $this->color;
- }
- }
- ?>
ClassFactory.php
- <?php
- /**
- * @author Gonn, http://www.nowamagic.net/
- */
- class ClassFactory {
- private $arr_conf;
- function ClassFactory($config_file){
- //读取配置文件内容
- $handle = fopen($config_file, r);
- $content = fread($handle, filesize($config_file));
- fclose($handle);
- //去除注释
- $content=preg_replace("<\/\/.*?\s>","",$content);
- //转成数组
- $this->arr_conf=json_decode($content,true);
- }
- function getBean($class_id){
- //查找匹配 $class_id 的类
- while(true){
- //挨个测试
- $conf=each($this->arr_conf);
- //找不到,返回 null
- if($conf==false) return null;
- if(strcmp($class_id,$conf["value"]["id"])===0){
- //如果匹配则装入类文件
- include_once($conf["value"]["class_file"]);
- //生成类的实例
- //print_r($conf["value"]["class_name"]);
- $obj=new $conf["value"]["class_name"]();
- //查找被设置的属性
- $arr_prop=$conf["value"]["properties"];
- while($prop=each($arr_prop)){
- //生成属性的设置方法 setXXX ,第一个字母大写
- $set_method="set". ucwords($prop["value"]["name"]);
- //调用设置方法,并设置预设值
- $obj->$set_method($prop["value"]["value"]);
- }
- //找到第一个,返回实例
- return $obj;
- }
- }
- }
- }
- ?>
Config.json
- //备注使用双反斜杆
- [
- {
- //类ID,方便工厂查找
- "id": "Apple",
- //类名
- "class_name":"Apple",
- //类文件
- "class_file":"Fruit.php",
- //属性设置
- "properties":[
- {
- "name":"color",
- "value":"Red"
- }
- ]
- },
- {
- "id": "Banana",
- "class_name":"Banana",
- "class_file":"Fruit.php",
- "properties":[
- {
- "name":"color",
- "value":"Yellow"
- }
- ]
- }
- ]
测试文件:test.php
- <?php
- include_once("ClassFactory.php");
- $factory = new ClassFactory("config.json");
- $fruit = $factory->getBean("Apple");
- echo $fruit->showColor() .'<br />';
- $fruit = $factory->getBean("Banana");
- echo $fruit->showColor() .'<br />';
- ?>
运行结果:
- Apple Color:Red
- Banana Color:Yellow
转自:http://blog.csdn.net/xiongping_/article/details/44077991