Creating Custom PHP Extensions with Zephir and Native Build Tools
Zephir-based Extension Workflow
1. Install Build Dependencies
sudo apt-get install gcc make re2c autoconf automake pkg-config
2. Install the Zephir Parser
git clone https://github.com/zephir-lang/php-zephir-parser.git
cd php-zephir-parser
phpize
./configure
make -j$(nproc) && sudo make install
echo "extension=zephir_parser.so" | sudo tee -a /etc/php/7.4/cli/conf.d/90-zephir.ini
3. Fetch the Zephir Compiler
wget -O /usr/local/bin/zephir https://github.com/zephir-lang/zephir/releases/download/0.16.3/zephir.phar
chmod +x /usr/local/bin/zephir
4. Scaffold a New Extension
zephir init Greet
cd Greet/greet
5. Write the Zephir Source
greet.zep
namespace Greet;
class Say
{
public static function hi(string $name = "World") -> string
{
return "Hello, " . $name . "!";
}
}
6. Compile and Install
# Ensure exec, shell_exec, system are not in disable_functions
sed -i 's/disable_functions.*//' /etc/php/7.4/cli/php.ini
cd ../..
zephir build
sudo cp ext/modules/greet.so $(php-config --ion-dir)
echo "extension=greet.so" | sudo tee -a /etc/php/7.4/cli/conf.d/99-greet.ini
sudo systemctl restart php7.4-fpm
7. Quick Test
php -r "echo \Greet\Say::hi('Zephir');"
Native C Extension Workflow (PHP 7.4.32)
1. Prepare PHP Source
cd /usr/local/src
wget https://www.php.net/distributions/php-7.4.32.tar.gz
tar -xzf php-7.4.32.tar.gz
cd php-7.4.32/ext
2. Generate Skeleton
./ext_skel.php --ext mathplus
3. Configure Build
Edit mathplus/config.m4 and uncomment the lines that enable the extension:
PHP_ARG_ENABLE(mathplus, whether to enable mathplus support,
[ --enable-mathplus Enable mathplus support])
4. Implement Functionality
mathplus/mathplus.c
PHP_FUNCTION(mathplus_add)
{
double a, b;
ZEND_PARSE_PARAMETERS_START(2, 2)
Z_PARAM_DOUBLE(a)
Z_PARAM_DOUBLE(b)
ZEND_PARSE_PARAMETERS_END();
RETURN_DOUBLE(a + b);
}
static const zend_function_entry mathplus_functions[] = {
PHP_FE(mathplus_add, NULL)
PHP_FE_END
};
5. Build and Install
cd mathplus
phpize
./configure --with-php-config=/usr/bin/php-config
make -j$(nproc) && sudo make install
echo "extension=mathplus.so" | sudo tee -a /etc/php/7.4/cli/conf.d/99-mathplus.ini
sudo systemctl restart php7.4-fpm
6. Verify
php -r "echo mathplus_add(3.5, 4.5);"