安装phpcpp
我们不赘述为什么试用phpcpp 进行php拓展库的开发,我们直接进入实践
下载并安装PHP-CPP 库
- 获取PHP-CPP 库代码
$ git clone https://github.com/CopernicaMarketingSoftware/PHP-CPP.git
- 安装
- 切换到PHP-CPP 源代码目录,其中应该包含Makefile 文件,它是一个包含编译器设置和指令的文件,在该目录下运行make启动编译器并构建库
$ make
- make install 安装到系统
$ sudo make install
第一个拓展
- 在官网下载一个空的扩展包demo空demo下载,在demo文件中包含一个 Makefile编译器说明文件,一个特定于扩展的 php.ini 文件,当然还有 *.cpp 文件
- Makefile 文件基本不需要修改,我们最主要关注 NAME(拓展名称),INI_DIR(ini 目录);
#
# Name of your extension
#
# This is the name of your extension. Based on this extension name, the
# name of the library file (name.so) and the name of the config file (name.ini)
# are automatically generated
#
NAME = tiway
#
# Php.ini directories
#
# In the past, PHP used a single php.ini configuration file. Today, most
# PHP installations use a conf.d directory that holds a set of config files,
# one for each extension. Use this variable to specify this directory.
#
INI_DIR = /etc/php/7.3/cli/conf.d/
- 拓展名.ini 初始拓展名,这个文件主要是在Make 编译的时候要用到里面很简单就是拓展的名称
extension=tiway.so
- main.cpp cpp扩展的实现,我们按照官网尝试写一个输出函数
#include <phpcpp.h>
#include <iostream>
void example()
{
// the C++ equivalent of the echo() function
Php::out << "example output" << std::endl;
// generate output without a newline, and ensure that it is flushed
Php::out << "example output" << std::flush;
// or call the flush() method
Php::out << "example output";
Php::out.flush();
// just like all PHP functions, you can call the echo() function
// from C++ code as well
Php::echo("Example output\n");
Php::Value
}
/**
* tell the compiler that the get_module is a pure C function
*/
extern "C" {
/**
* Function that is called by PHP right after the PHP process
* has started, and that returns an address of an internal PHP
* strucure with all the details and features of your extension
*
* @return void* a pointer to an address that is understood by PHP
*/
PHPCPP_EXPORT void *get_module()
{
// static(!) Php::Extension object that should stay in memory
// for the entire duration of the process (that's why it's static)
static Php::Extension extension("tiway", "1.0");
// @todo add your own functions, classes, namespaces to the extension
extension.add<example>("example");
// return the extension
return extension;
}
}
- 在文件目录下执行 make && make install
$ make && make install
如果已经编译过则
$ make clean && make && make install
- 查看拓展是否安装成功
php -m | grep tiway
在拓展目录新建php文件,test.php
<?php
example();
//example output
//example outputexample output
?>
总结
- 写cpp拓展,至少对cpp 有一定的了解,比如了解cpp 包的引入及常用的包如所用的
- PHP-CPP 拓展库目前仅支持linux环境