php اکستنشن خودمون رو بسازیم؟یه موضوعی که شاید براتون جالب باشه اکستنشن های
php هستقطعا کسایی که با
php کار میکنن با این اکستنشن ها آشنا هستنمثل
curl , gd , pdo , mysqli و....و یک سری ابزار توسعه داده شده به زبان های C یا C++ هستند که قابلیت هایی رو به
php اضافه میکنن.هدف این پست تعریف اکستنشن ها نیست بلکه ساخت یک اکستنشن شخصی هست که میتونه جالب باشه برای همه.
1- در مرحله اول باید محیط توسعه رو آماده کنیم
من توی این آموزش از یک دبین بیس (
WSL-Ubuntu) استفاده کردم که کاربر های ویندوزهم میتونن با wsl کار کننو از کامپایلر
GCC، ادیتور هم که اهمیتی ندارهدر ادامه ابزار رو نصب میکنیم
sudo apt-get install build-essential php8.0 php8.0-dev
2- در مرحله بعد باید فایل کانفیگ اکستنش رو درست بکنیم به نام config.m4 با مقادیر زیر:PHP_ARG_ENABLE(php_helloworld, Whether to enable the HelloWorldPHP extension, [ --enable-helloworld-php Enable HelloWorldPHP])
if test "$PHP_HELLOWORLD" != "no"; then
PHP_NEW_EXTENSION(php_helloworld, php_helloworld.c, $ext_shared)
fi
3- در مرحله سوم شروع به کد زدن اکستنشن خودمون میکنیم (این اکستنشن صرفا یه تابع helloworld درست میکنه)کد ها توی دو فایل
php_helloworld.h و php_helloworld.h نوشته میشن که در ادامه کد هارو میبینید:php_helloworld.h:
// we define Module constants
#define PHP_HELLOWORLD_EXTNAME "php_helloworld"
#define PHP_HELLOWORLD_VERSION "0.0.1"
// then we declare the function to be exported
PHP_FUNCTION(helloworld_php);
php_helloworld.c:// include the PHP API itself
#include <php.h>
// then include the header of your extension
#include "php_helloworld.h"
// register our function to the PHP API
// so that PHP knows, which functions are in this module
zend_function_entry helloworld_php_functions[] = {
PHP_FE(helloworld_php, NULL)
{NULL, NULL, NULL}
};
// some pieces of information about our module
zend_module_entry helloworld_php_module_entry = {
STANDARD_MODULE_HEADER,
PHP_HELLOWORLD_EXTNAME,
helloworld_php_functions,
NULL,
NULL,
NULL,
NULL,
NULL,
PHP_HELLOWORLD_VERSION,
STANDARD_MODULE_PROPERTIES
};
// use a macro to output additional C code, to make ext dynamically loadable
ZEND_GET_MODULE(helloworld_php)
// Finally, we implement our "Hello World" function
// this function will be made available to PHP
// and prints to PHP stdout using printf
PHP_FUNCTION(helloworld_php) {
php_printf("Hello World! (from our extension)\n");
}
4- حالا نوبت build کردنش هست:اول محیط ساخت رو آماده میکنیم
phpizeسپس بیلد رو کانفیگ میکنیم و افزونه رو فعال می کنیم:
./configure --enable-php-helloworldور در نهایت بیلدش میکنیم
make
sudo make install
5- حالا نوبت تست هستمیتونید
extension=php_helloworld رو به فایل php.ini خودتون اضافه کنید و سپس تابع helloworld_php() رو توی یک فایل php فراخوانی کنید یا در ترمینال خودتون درستور زیر رو بزنیدphp -d extension=php_helloworld.so -r 'helloworld_php();'و در نهایت زیبایی رو میبینید
Result:
Hello World! (from our extension)
منبع
.