包含(Requires)

Phalcon API 提供了 phalcon_require 函数实现 PHP 的 require 功能,在实际开发过程中,进程会在一个文件中包含另一个或者直接从另一个文件中返回一组数据。

实例(instance)

假如我们要实现如下 PHP 代码的功能:

  1. $file = "config.php";
  2. $config = require($file);

在 Phalcon 中使用 API 实现起来也一样简单:

  1. zval config = {};
  2.  
  3. phalcon_require_ret(&config, "config.php");

内部实现(implementation)

  1. // Check file exists
  2. if (VCWD_STAT(file_name, &file_sb) == 0) {
  3. // Whether it is a regular file
  4. if (S_ISREG(file_sb.st_mode)) {
  5. // Open file
  6. if (( fh.handle.fp = VCWD_FOPEN(file_name, "r") )) {
  7. fh.filename = file_name;
  8. fh.type = ZEND_HANDLE_FILENAME;
  9. fh.free_filename = 0;
  10. fh.opened_path = NULL;
  11.  
  12. // Compile file
  13. op_array = zend_compile_file(&fh, ZEND_REQUIRE TSRMLS_CC);
  14.  
  15. // Delete file handle
  16. zend_destroy_file_handle(&fh);
  17.  
  18. // Check compile results
  19. if (op_array) {
  20. zval result;
  21. ZVAL_UNDEF(&result);
  22.  
  23. // Access to compile the results
  24. zend_execute(op_array, &result);
  25. // result => $config
  26.  
  27. ZVAL_COPY(&temp, &result);
  28.  
  29. // Delete compile results
  30. destroy_op_array(op_array);
  31. efree(op_array);
  32. if (!EG(exception)) {
  33. zval_ptr_dtor(&result);
  34. }
  35. }
  36. }
  37. }
  38. }

此时 result 变量就是我们案例中的 $config 变量,当然还可以使用 zend_include_or_eval 实现文件的包含,支持类型有:

  • ZEND_INCLUDE
  • ZEND_INCLUDE_ONCE
  • ZEND_REQUIRE
  • ZEND_REQUIRE_ONCE