如何在 CodeIgniter 中从不同的 XML 向模型提供数据


How to feed data to model in CodeIgniter from different XMLs

我有一个带有Xml_model的CodeIgniter应用程序:

<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Xml_model extends CI_Model {
        private $xml;
        public function __construct() {
          parent::__construct();
          $this->xml = simplexml_load_file(base_url('xml/example.xml'));
        }
        public function getAllTags() {
          return array_unique($this->xml->xpath('descendant::Keyword'));
        }
        public function getLinks($nodeName) {
          return $this->xml->xpath('/Documents/TabPage/Node[@name="'.$nodeName.'"]/Links/Link');
        }
        public function getTabs() {
          return $this->xml->xpath('/Documents/TabPage/@name');
        }
        public function getNodes($tabName) {
          return $this->xml->xpath('/Documents/TabPage[@name="'.$tabName.'"]/Node/@name');
        }
        public function getPath($nodeName) {
          return $this->xml->xpath('/Documents/TabPage/Node[@name="'.$nodeName.'"]/Path');
        }
        public function search($tagName) {
          return $this->xml->xpath('//*[Keyword="'.$tagName.'"]/parent::Node/@name');
        }
}
?>

我希望能够使用不同的 XML 加载此模型。这些 XML 由站点上的下拉菜单选择。XML 正在定义网站上的导航,因此从下拉列表中选择 XML 后,页面将重新加载并使用新选择的 XML 执行此操作。但我不知道我该怎么做,因为我无法在 CodeIgniter 中使用参数加载模型。

下拉列表:

  <div class="xml">
    <form method="post" id="xml-form">
      <select name="xml-select">
        <?php
          foreach(glob('xml/*.xml') as $filename) {
            echo '<option value="'.$filename.'">'.explode(".",explode("/",$filename)[1])[0].'</option>';
          }
        ?>
      </select>
      <button type="submit"><span class="glyphicon glyphicon-refresh"></span></button>
    </form>
  </div>

我能想到的两种方法来解决这个问题。

一:添加一个 init 函数,该函数采用要加载的文件的名称。加载模型后立即调用此函数。

class Xml_model extends CI_Model 
{
    private $xml;
    public function init($file) {
        $this->xml = simplexml_load_file(base_url($file));
    }

另一种选择是创建一个新的库类,而不是扩展CI_Model。根据你展示的内容,没有明显的要求这是一个"模型"类。

可以在加载时将参数传递给构造函数。我看到的唯一(非常小的)棘手部分是对base_url()的调用将要求您获取对 CI"超级对象"的引用。 或者,可以解析完整路径并将其传递给构造函数,从而消除在自定义类中调用base_url()的需要。