【问题标题】:Best way to implement standard PHP classes in CodeIgniter with Controllers使用控制器在 CodeIgniter 中实现标准 PHP 类的最佳方法
【发布时间】:2013-01-03 16:28:36
【问题描述】:

我正在尝试在 CI 中模仿这些简单的 PHP 类定义

<?php
class Student
{
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

class SportsStudent extends Student {

    private $sport;

    public function __construct($name) {
        parent::__construct($name);
        $this->sport = "Tennis";
    }

    public function getSport() {
        return $this->sport;
    }
}

$s1 = new Student("Joe Bloggs");
echo $s1->getName() . "<br>";

$s2 = new SportsStudent("John Smith");
echo $s2->getName() . "<br>";
echo $s2->getSport() . "<br>";
?>

我想知道如何最好地处理它,我确实尝试为这两个类创建一个控制器,但在继承方面遇到了麻烦,我被告知最好扩展 CI_Controller 但我无法理解它,这似乎有点矫枉过正,不推荐使用。

最好只保留这些标准类并从我的控制器调用它们吗?

这是我在系统上的第一次基于 MVC 的尝试,也是我的第一个 CI 项目,希望能有一些指点。

【问题讨论】:

  • 请在问题中包含代码示例(尤其是相对较短的示例),而不是通过可能对页面的未来访问者无效的链接;-)

标签: php codeigniter class


【解决方案1】:

这些类应该表示为模型,而不是控制器。所以你会做这样的事情:

class Student extends CI_Model {
    ...
}

class SportsStudent extends Student {
    ...
}

您应该将 Student 模型放在 application/core 文件夹(对于 CI 2+)或 application/libraries 文件夹(对于 CI 1.8 或更低版本 - 以及将 CI_Model 更改为 Model)。

【讨论】:

  • 我还想知道如何将我的构造函数从 SportsStudent 传递给 Student?通常我会做 SportsStudent(parent::__construct($var1, $var2)) 但似乎 CI 不喜欢这样?
  • 另外,我是否将 Student 和 SportsStudent 都放在 application/core 中?
  • 好的,我设法解决了这个问题。我需要自动加载我的 Student 类才能识别 SportsStudent。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-16
  • 2016-04-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多