您的位置 首页 php

不要再天天写表单了,淘宝大牛教你零基础写 PHP 扩展

很多 PHPer 天天写表单,不知如何提升。如果你已经熟悉了数据集和服务器端的优化,不妨试试通过 PHP 扩展向系统层进军。当原有的 PHP 代码实现出现性能瓶颈,可以考虑通过 PHP 扩展实现;纯 PHP 代码无法实现的功能,可以考虑通过 PHP 扩展调用其他相关库实现。既能提升业务能力,又能帮助大家逐渐通过扩展了解 PHP 源代码层的运作机制。

扩展入门较难,这里特别推荐淘宝大牛信海龙老师的入门课程,手把手教会你只要一块钱。

我们精选出文集中的第二章内容,以供免费试读。如果你不喜欢付费课程,可以通过 PHP 手册第二部分进行学习()

从hello world开始(试读)

以下内容以 PHP7 作为基础,讲解如何从零开始创建一个 PHP 扩展。示例中,我们将实现如下功能:

输出内容:

  1. $ php ./test.php

  2. $ hello word

在扩展中实现一个 say 方法,调用 say 方法后,输出 hello word。

第一步:生成代码

PHP 为我们提供了生成基本代码的工具 ext_skel。这个工具在 PHP 源代码的 ./ext 目录下。

  1. $ cd php_src/ext/

  2. $ ./ext_skel --extname=say

extname 参数的值就是扩展名称。执行 ext_skel 命令后,这样在当前目录下会生成一个与扩展名一样的目录。

第二步,修改 config . m4 配置文件

config.m4 的作用就是配合 phpize 工具生成 configure 文件。configure 文件是用于环境检测的。检测扩展编译运行所需的环境是否满足。现在我们开始修改config.m4 文件。

  1. $ cd ./say

  2. $ vim ./config.m4

打开,config.m4 文件后,你会发现这样一段文字。

  1. dnl If your extension references something external, use with:

  2. dnl PHP_ARG_WITH(say, for say support,

  3. dnl Make sure that the comment is aligned:

  4. dnl [ --with-say Include say support])

  5. dnl Otherwise use enable:

  6. dnl PHP_ARG_ENABLE(say, whether to enable say support,

  7. dnl Make sure that the comment is aligned:

  8. dnl [ --enable-say Enable say support])

其中,dnl 是注释符号。

上面的代码说,如果你所编写的扩展如果依赖其它的扩展或者 lib 库,需要去掉 PHP_ARG_WITH 相关代码的注释。否则,去掉 PHP_ARG_ENABLE 相关代码段的注释。我们编写的扩展不需要依赖其他的扩展和 lib 库。

因此,我们去掉 PHP_ARG_ENABLE 前面的注释。去掉注释后的代码如下:

  1. dnl If your extension references something external, use with:

  2. dnl PHP_ARG_WITH(say, for say support,

  3. dnl Make sure that the comment is aligned:

  4. dnl [ --with-say Include say support])

  5. dnl Otherwise use enable:

  6. PHP_ARG_ENABLE(say, whether to enable say support,

  7. Make sure that the comment is aligned:

  8. [ --enable-say Enable say support])

第三步,代码实现

修改 say.c 文件。实现 say 方法。 找到PHP_FUNCTION(confirm_say_compiled),在其上面增加如下代码:

  1. PHP_FUNCTION(say)

  2. {

  3. zend_string *strg; strg = strpprintf(0, "hello word");

  4. RETURN_STR(strg);

  5. }

找到 PHP_FE(confirm_say_compiled, 在上面增加如下代码:

  1. PHP_FE(say, )

修改后的代码如下:

  1. const zend_function_entry say_functions = {

  2. PHP_FE(say, ) /* For testing, remove later. */

  3. PHP_FE(confirm_say_compiled, ) /* For testing, remove later. */

  4. PHP_FE_END /* Must be the last line in say_functions */

  5. };

  6. /* }}} */

第四步,编译安装

编译扩展的步骤如下:

  1. $ phpize

  2. $ ./configure

  3. $ make && make install

修改 php.ini 文件,增加如下代码:

  1. [say]

  2. extension = say.so

然后执行,php -m 命令。在输出的内容中,你会看到 say 字样。

第五步,调用测试

自己写一个脚本,调用 say 方法。看输出的内容是否符合预期。

  1. <?php

  2. echo say;

  3. ?>

圈主介绍:

信海龙老师于 2013 年加入 阿里巴巴 ,拥有十年互联网开发经验。为帮助写 PHP 的小伙伴提高提高业务能力,特意在知加创建圈子『零基础学习PHP扩展开发』,用于与 PHP 扩展开发初学者分享、交流。

零基础学习 PHP 扩展开发

也可点击【阅读原文】加入圈子

文章来源:智云一二三科技

文章标题:不要再天天写表单了,淘宝大牛教你零基础写 PHP 扩展

文章地址:https://www.zhihuclub.com/153357.shtml

关于作者: 智云科技

热门文章

网站地图