php spl_autoload_register 实现简单的 API 模式

spl_autoload_register() 是 php 一个自动加载类库的方法;
其属于 autoload 家族的一个成员。详细的介绍就不多赘述了,直接传送门

直接上代码
代码目录:WkTest
入口文件 <index.php>

<?php
$url = explode( '/', strstr( $_SERVER['PHP_SELF'], 'index.php') );
$module = isset( $url[1] )?$url[1]:'Wk';
$action = isset( $url[2] )?$url[2]:'Show';

function loadClass($class) {
    $file = realpath(__DIR__).'/'.$class.'.class.php';
    if( !is_file( $file ) ){
        header( 'HTTP/1.1 404 Not Found' );
        // echo $class.' is not found ';
        exit();
    }else{
        include $file;
    }
}
spl_autoload_register('loadClass');

if( !class_exists( $module ) || !method_exists( $module, $action ) ){
    header( 'HTTP/1.1 404 Not Found' );
    // echo $module.'/'.$action.' is not found ';
    exit();
}

$obj = new $module;
$obj->$action();
exit();
?>

类文件
Wk.class.php

<?php
class Wk {

    function __construct() {
        // echo "Wk __construct() \r\n";
    }
    static public function show() {
        $param = $_GET;
        $message = isset( $param['message'] )?$param['message']:'';
        echo $message."\r\n<br>Hello, World!";
    }
}
?>

完成,直接访问
http://localhost/WkTest/index.php
http://localhost/WkTest/index.php/Wk/Show?message=“wk”

是不是超级简单,如果要支持更复杂的逻辑,就要自己多实践了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值