php7扩展自动加载类.

使用php扩展来开发框架似乎越来越来成来主流了,如phalcon,鸟哥的yaf。这些框架都以高性能著称,相对纯php使用的框架而,php扩展实现的框架更快,不会带来额外的系统消耗。在php启动时便已加载了框架,并且常驻内存。

几乎所有框架都带自动加载类,以便更好的管理代码。php实现方法这里就不多介绍了,读者可以自行百度。这里将介绍如何在php扩展中实现。

扩展中的实现原理与php实现基本原理一致,都是基于 spl_autoload_register 函数实现。

ZEND_METHOD(lxx_request,run) {
    zval arg;//参数
    zval * pthis = getThis();//当前类

    array_init(&arg);//初始化数据,
    Z_ADDREF_P(pthis);

    add_next_index_zval(&arg, pthis);
    add_next_index_string(&arg, "load");//当前类的中load的方法,表态方法(ZEND_ACC_STATIC)

    /*zend_call_method_with_1_params arg为数组参娄 php 代码spl_autoload_register(['lxx\request','load']);*/
    zend_call_method_with_1_params(NULL, NULL, NULL, "spl_autoload_register", NULL, &arg);

   zval_ptr_dtor(&arg);
}


/*字符替换*/
static void str_replace(char *str,char o,char n) {
    while(*str != '\0') {
        if (*str == o) {
            *str = n;
        }
        str++;
    }
}

 ZEND_METHOD(lxx_request,load) {
    zend_string *cl;       /*php7中新增的数据类型 全用大写S接收,小写s则char指针*/
    long cl_len = 0;
    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "S", &cl) == FAILURE) {
        RETURN_FALSE;
    }

    zend_file_handle zfd;
    zend_op_array *op_array;
    smart_str str = {0};
    smart_str_appendl(&str,cl->val,cl->len);
    smart_str_appendl(&str,".php",sizeof(".php")-1);
    smart_str_0(&str);

    str_replace(str.s->val,'\\','/');
    zfd.type = ZEND_HANDLE_FILENAME;
    zfd.filename = str.s->val;
    zfd.free_filename = 0;
    zfd.opened_path = NULL;
    zfd.handle.fp = NULL;

    op_array = zend_compile_file(&zfd,ZEND_INCLUDE); 

    if (zfd.opened_path) {
        zend_hash_add_empty_element(&EG(included_files),zfd.opened_path);
    }
    zend_destroy_file_handle(&zfd);

    if(op_array) {
        zend_execute(op_array,NULL);
        //zend_exception_restore();

        destroy_op_array(op_array);
        efree(op_array);

    }

    //zend_printf("<BR>%s 有没有啊?帅不帅啊?",str.s->val);
    zend_string_release(cl);
    smart_str_free(&str);
}

注册当前类

ZEND_MODULE_STARTUP_D(lxx_request) {
    zend_class_entry ce;
    memset(&ce,0,sizeof(zend_class_entry));
    INIT_CLASS_ENTRY(ce,"Lxx\\request",lxx_request_functions);
    lxx_request_ce = zend_register_internal_class_ex(&ce,NULL);
    //lxx_request_ce->ce_flags = ZEND_ACC_EXPLICIT_ABSTRACT_CLASS;
}

测试

$cl = new Lxx\request();
$cl->run();

$ab = new abc\ab();
echo $ab->test("lxx");

在abc目录下建立ab.php

namespace abc;
class ab {
    //php7新特性写法,
    public function test(string $name) :string {
         return "Hi : ".$name;
    }
}

输出

Hi : lxx


源文来自:www.lxxbl.com

转载于:https://my.oschina.net/u/261704/blog/474958

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值