PHP接口请求自动分发调用对应类中的函数

实现原理:
在基类中定义一个公共的调用函数,这里我定义函数名为 handleActionhandleAction 函数要实现的功能是首先获取调用该函数的子类名称,然后得到子类的实例,最后约定请求某一接口时,通过传参 handle=要调用的接口函数名 ,即可实现接口请求的自动分发了。

在往下查看示例之前,你需要对PHP中 __CLASS__get_class()get_called_class() 的使用和区别有一定的了解,可以查看我的另一篇文章:PHP方法继承调用,如何获取子类名称?get_class() 和 get_called_class()

1、为了减少多次new带来的资源消耗,我们要使用单例模式

在基类中,可以定义实现单例模式的方法,然后在继承它的子类中调用:

class Base {

	private static $instance = array();
	
	/**
     * 单例模式
     */
	static function getInstance() {
   		$className = get_called_class();
   		if (isset(self::$instance[$className])) {
        	return self::$instance[$className];
   		}
   		self::$instance[$className] = new $className;
   		return self::$instance[$className];
	}
}

class Child extends Base {
}

$child = Child::getInstance();    // 子类实例

通过以上实现,就可以得到子类 child 的单例实例了,如果有更多的子类,通过以上实现也可以得到对应子类的单例实例,而不用在每个子类中重复声明单例实现方法,是不是很方便呢。

2、实现自动分发调用对应类中的接口函数
其实开头已经说过,实现起来不难,就是根据接口请求时的传参,然后根据传参值,自动分发调用当前类中的对应接口函数:

class Base {

	private static $instance = array();
	
	/**
     * 单例模式
     */
	static function getInstance() {
   		$className = get_called_class();
   		if (isset(self::$instance[$className])) {
        	return self::$instance[$className];
   		}
   		self::$instance[$className] = new $className;
   		return self::$instance[$className];
	}

	/**
     * 根据请求接口时传参,自动分发调用对应类实例中的可执行函数
     */
    static function handleAction()
    {
        $handleFunction = $_REQUEST['handle']; //  请求传参:handle=要调用的接口函数名,handle参数名可自行定义
        $instance = self::getInstance(); // 获取当前类调用 handleAction() 的单例
        $currClassName = get_class($instance); // 根据实例获取当前类名
        if (is_callable($currClassName, $handleFunction)) { // 判断 $handleFunction 函数在当前类中是否可调用
            echo $instance->$handleFunction();
        } else {
            echo "Error: Method '" . $handleFunction . "' of class '" . $currClassName . "' does not exist!";
        }
    }
}

class ChildA extends Base {
	function getInfo() {
		echo 'This is ChildA';
	}
	... // 其他方法
}

class ChildB extends Base {
	function getInfo() {
		echo 'This is ChildB';
	}
	... // 其他方法
}

然后在接口中引用:
接口文件A A.php

<?php

require_once 'Base父类文件';
require_once 'ChildA子类文件';
// 当然以上你可以使用 spl_autoload_register 实现类的自动加载,此处只为了演示,就不作实现了。

ChildA::handleAction();
?>

接口文件B B.php 同上。

最后你就可以调用接口时,不管是 get 还是 post 请求,只需带上参数 handle=要调用的接口函数名 即可调用对应子类的接口函数:

// 示例
requireUrl: 
	server/api/A.php?handle=getInfo
	server/api/B.php?handle=getInfo
	// server/api/B.php?handle=其他方法名


// 结果:
This is ChildA
This is ChildB

以上即可实现通过简洁的代码,将请求自动分发到对应类的接口函数了,是不是很简单呢。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值