【问题标题】:CodeIgniter can't call function from model in controllerCodeIgniter 无法从控制器中的模型调用函数
【发布时间】:2013-10-04 12:11:09
【问题描述】:

我对 Codeigniter 还很陌生,正在尝试从我的模型中调用一个函数,但我无法让它工作。谁能看到我在这里做错了什么?

控制器(farm.php):

<?php defined('BASEPATH') OR exit('No direct script access allowed');

    class Farm extends CI_Controller {

        function __construct()
        {
            parent::__construct();
            $this->load->model('harvest_first');
        }

        function harvest()
        {

            echo $this->harvest_first->harvest();
        }   
    }

模型(harvest_first.php):

<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

    class Harvest_first extends CI_Model
    {

        public function __construct()
        {
            parent::__construct();
        }

        public function harvest(){
            return "THE FUNCTION";
        }
    }
?>

我试图呼应“功能”,但无论我做什么,我都无法让它按预期工作。

谢谢, 西蒙

【问题讨论】:

  • 您遇到什么错误?从外观上看没有错误。
  • 你是如何调用你的函数的?你试试像your_host/farm/harvest这样的网址吗?
  • 这不是错误,只是没有按预期工作。我从 website.com/farm/harvest 调用它,页面加载正常,没有错误,但该功能无法正常工作。如果我在控制器中的函数调用上方和下方添加手动回显,则上面显示但第二个没有。
  • Harvest_first 模型应该是Harvest_first_model。任何模型都应在类名末尾包含_model
  • @machineaddict 你从哪里得到的?我很确定它不是那样的,手册中也没有提及(甚至在提供的示例中也没有):ellislab.com/codeigniter/user-guide/general/models.html

标签: php codeigniter


【解决方案1】:

试试这个

class Harvest_first extends CI_Model

改为:

class Harvest_first_model extends CI_Model

在这样的控制器调用中:

 $this->load->model('harvest_first_model');

 $this->harvest_first_model->harvest();

【讨论】:

  • 做到了,非常感谢您从未意识到您必须在名称中包含模型。
  • 你从哪里得到这个的?我很确定不是那样的,手册中也没有提及(甚至在提供的示例中也没有):ellislab.com/codeigniter/user-guide/general/models.html
  • 不,CI中没有naming conventions的规则。
  • 倾向于同意伙计们。不要相信任何命名约定都需要模型。怀疑 Simon 忘记执行 load->model 语句或拼写错误或错过函数调用中的模型名称。不是想变得聪明。只是不希望有人对它的工作原理有错误的认识。
【解决方案2】:

Check here

  • 依赖你的模型不需要加“_model”
  • 只需加载模型并使用 autoload.php 并在其中添加模型,这是一个很好的做法

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-08-25
    • 1970-01-01
    • 2012-04-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多