Zephir是一個開源的用於簡化PHP擴展的建立和維護的語言。它使得不擅長C/C++的PHP開發人員也能寫出PHP擴展。Zephir是Zend Engine/PHP/Intermediate縮寫,讀音爲zephyr。php
Zephir在語法上跟PHP有不少類似之處,PHP開發人員能夠很快上手,但也有不少地方上的不一樣須要咱們去學習。下面是Zephir一些主要的特點:html
要使用Zephir和編譯出一個PHP擴展,須要先安裝如下的依賴:mysql
這裏選擇使用git
的方式獲取源代碼並進行安裝:git
bash$ git clone https://github.com/phalcon/zephir $ cd zephir $ ./install-json $ ./install -c
若是已經安裝了
json-c
,那麼能夠忽略./install-json
這一步。github
經過運行zephir命令驗證下是否安裝成功:web
bash$ zephir help _____ __ _ /__ / ___ ____ / /_ (_)____ / / / _ \/ __ \/ __ \/ / ___/ / /__/ __/ /_/ / / / / / / /____/\___/ .___/_/ /_/_/_/ /_/ Zephir version 0.7.1b Usage: command [options] Available commands: stubs Generates extension PHP stubs install Installs the extension (requires root password) fullclean Cleans the generated object files in compilation build Generate/Compile/Install a Zephir extension generate Generates C code from the Zephir code clean Cleans the generated object files in compilation builddev Generate/Compile/Install a Zephir extension in development mode compile Compile a Zephir extension version Shows the Zephir version api [--theme-path=/path][--output-directory=/path][--theme-options={json}|/path]Generates a HTML API help Displays this help init [namespace] Initializes a Zephir extension Options: -f([a-z0-9\-]+) Enables compiler optimizations -fno-([a-z0-9\-]+) Disables compiler optimizations -w([a-z0-9\-]+) Turns a warning on -W([a-z0-9\-]+) Turns a warning off
下面咱們使用Zephier來建立一個「hello world」擴展。sql
首先,咱們使用init
命令來初始化擴展的基本結構(假設咱們擴展的名稱爲「utils」):json
bash$ zephir init utils
成功運行後,咱們應該會獲得以下的目錄結構:api
bashutils/ ext/ utils/
ext
目錄裏放的是編譯器須要用到的代碼,不用理會,咱們的Zephir代碼將放在跟擴展名同名的utils
裏。安全
咱們在utils
目錄下建立一個文件:greeting.zep
,並編寫代碼:
phpnamespace Utils; class Greeting { public static function say() { echo "hello world!"; } }
這裏不深刻Zephir的語法,可是能夠看到語法跟PHP很相似,上面的代碼定義了一個類Greeting
和一個方法say()
。
Zephir的語法詳情能夠參考官方的文檔:http://zephir-lang.com/language.html。
接下來,咱們回到utils
根目錄下並運行build
命令編譯出擴展:
bash$ zephir build Preparing for PHP compilation... Preparing configuration file... Compiling... Installing... Extension installed! Add extension=utils.so to your php.ini Don't forget to restart your web serverp
編譯成功後,咱們在PHP配置文件裏增長如下一行:
iniextension=utils.so
經過以下命令查看咱們的擴展是否正常加載:
bashphp -m [PHP Modules] ... memcached mysql mysqli mysqlnd openssl utils ...
若是看到咱們擴展的名字,則證實已成功加載。
而後咱們在PHP裏調用say()
方法:
php<?php echo Utils\Greeting::say(), "\n";
正常的話會輸出:hello world!
。至此咱們也完成了咱們的第一個擴展。