Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/codeigniter/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 实对象与MVC_Php_Codeigniter_Instantiation - Fatal编程技术网

Php 实对象与MVC

Php 实对象与MVC,php,codeigniter,instantiation,Php,Codeigniter,Instantiation,在此之前,我总是这样编码对象: // initialization $husband = new User('Bob'); $wife = new User('Sarah'); // action $husband->dance(); $wife->read(); // get echo "The husband is ".$husband->getAge()." years old"; // load model $this->load->model('us

在此之前,我总是这样编码对象:

// initialization
$husband = new User('Bob');
$wife = new User('Sarah');

// action
$husband->dance();
$wife->read();

// get
echo "The husband is ".$husband->getAge()." years old";
// load model
$this->load->model('user');

// action
$this->user->dance('Bob');
$this->user->read('Sarah');

// get
echo $this->user->getAge('Bob');
但对于CodeIgniter(和MVC),这样想似乎更好:

// initialization
$husband = new User('Bob');
$wife = new User('Sarah');

// action
$husband->dance();
$wife->read();

// get
echo "The husband is ".$husband->getAge()." years old";
// load model
$this->load->model('user');

// action
$this->user->dance('Bob');
$this->user->read('Sarah');

// get
echo $this->user->getAge('Bob');
但在这种情况下,如何处理“真实对象”?例如,对象“Bob”和对象“Sarah”? 也许我遗漏了什么,但对我来说,这个模型(第二个例子)!=对象(第一个示例)。 这个物体的概念是不相容的吗


我有目录视图、目录控制器和目录模型。我还应该有一个“对象”目录吗?

Codeigniter基于

在软件工程中,singleton模式是一种设计模式,通过将类的实例化限制为一个对象来实现singleton的数学概念。当需要一个对象来协调整个系统中的操作时,这非常有用。这一概念有时被推广到只有一个对象时运行效率更高的系统,或者将实例化限制在一定数量的对象上的系统


如果仍要使用CI,可以执行以下操作:

// load the class. I think there was a second parameter to avoid instantiation, not sure though. Either way, this will at least load the class
$this->load->model('user',false);

$husband = new User('Bob');
$wife = new User('Sarah');

// action
$husband->dance();
$wife->read();

这仍然是MVC。丑陋的类加载部分就在那里,因为CI在引用时没有类自动加载,所以您必须手动进行。也许你可以以某种方式集成一个。如果使用不当,singleton就会变成幽灵,这是一个常见的错误。对我来说也是如此:-(@Kowser:事实上,singleton是一种反模式:它不能正确使用。哇。只要发现singleton是什么。非常感谢!但是现在,我该怎么做?创建一个“对象”没有Singleton?o的另一个PHP框架的目录或更改_O@user1014813如果你有足够的兴趣学习另一个简单的框架,那就是kohana。我不得不放弃Codeigniter做我的第一个项目,这对我来说是可怕的经历。但显然这是我的观点。如果你需要一个不会教你坏习惯的框架(如使用单例反模式),您没有太多的选择:微框架或框架。您不会后悔选择其中一个。即使您最终使用了其他东西,在阅读他们的文档时所学到的最佳实践也将是值得的。@HappyDeveloper Silex对于我的项目来说似乎有点太轻,而Symfony太大了……您认为呢out Kohana?它也教坏习惯吗?谢谢你的回答。我没有深入研究Kohana,但因为它最初是基于CI的,所以我不会期望太多。你应该使用你认为最适合你的项目的框架(即使是CI),同时为将来的项目学习Sf2,或者只是为了学习良好的实践。