The Minimal PHP5 Extension Skeleton for Starters
To create an extension, you will need at least three files:
- config.m4
- ext_foo.c
- ext_foo.h
Here is a initial content of config.m4:
PHP_ARG_ENABLE(foo, whether to enable foo extension support,
[--enable-foo Enable foo extension support])PHP_NEW_EXTENSION(foo, php_foo.c, $ext_shared)
The PHP_ARG_ENABLE macro enables the option from ./configure script, you can do:
./configure --enable-foo
And you can add extra script in your config.m4 to check weather to compile your extension. The value of the configuration will be stored in $PHP_FOO variable. Since it’s boolean option, there will only be “yes” or “no”:
if test $PHP_FOO != "no"; then
PHP_NEW_EXTENSION(foo, php_foo.c, $ext_shared)
fi
However the code above is usually not used since your extension will be installed directly, not from the php-src build system.
./configure
Would just work for you.
And here is the minimal content of ext_foo.h
#ifndef _PHP_FOO_H
#define _PHP_FOO_H
#ifdef HAVE_CONFIG_H
#include “config.h”
#endif#ifdef ZTS
#warning php_ext_uv module will *NEVER* be thread-safe
#include <TSRM.h>
#endif#include <php.h>extern zend_module_entry foo_module_entry;PHP_FUNCTION(foo_hello);#endif
Here is the content of php_foo.c, a minimal extension source code must contains a zend_module_entry, And you usually need to define zend_function_entry to declare your extension functions:
#include "php_foo.h"PHP_MINIT_FUNCTION(foo);PHP_MSHUTDOWN_FUNCTION(foo);PHP_MINFO_FUNCTION(foo);#if COMPILE_DL_FOOZEND_GET_MODULE(foo)#endifstatic const zend_function_entry foo_functions[] = { PHP_FE(foo_hello, NULL) PHP_FE_END};zend_module_entry foo_module_entry = { STANDARD_MODULE_HEADER, "Foo", // your extension name foo_functions, // where you define your functions PHP_MINIT(foo), PHP_MSHUTDOWN(foo), NULL, // PHP_RINIT(foo) NULL, // PHP_RSHUTDOWN(foo) PHP_MINFO(foo), "0.1", STANDARD_MODULE_PROPERTIES};PHP_MINIT_FUNCTION(foo) { return SUCCESS;}PHP_MSHUTDOWN_FUNCTION(foo) { return SUCCESS;}PHP_MINFO_FUNCTION(foo) {}PHP_FUNCTION(foo_hello) { RETURN_TRUE;}
Finally just run commands to build your extension file:
phpize
./configure
make
One more thing, to customize the extension name instead of using “foo”, you can some perl commands to replace the identifiers:
perl -i -pe 's/foo/bar/g' config.m4 *.h *.c
perl -i -pe 's/Foo/Bar/g' config.m4 *.h *.c
perl -i -pe 's/FOO/BAR/g' config.m4 *.h *.c
Just replace “bar”, “Bar”, “BAR” with your new name and it will just work.