duanbarong4617 2013-08-13 14:34
浏览 29
已采纳

在CakePHP等框架中进行OOP

I thought I was pretty comfortable with the fundamentals of OOP in a few languages like Python and PHP, but I got a bit confused trying to figure out what's going on in certain situations in CakePHP.

Say for example I'm in a controller called TestsController but I want to look up data from another controller, such as OthersController. I'd do something like this

$this->loadmodel('Other');
$this->Other->find('all');

I understand that $this is a reference to the object of the class you're in, and Other clearly refers to OthersController, but what exactly is Other? Is it some kind of initialization variable? An Object? Something else? Does $this->Other become an object itself? If so, how does PHP/CakePHP do this, or is it just something inherent of PHP that it just "knows" to do so.

I found this example of something called method chaining, but it looks like using one object to call many actions.

<?php
class MyClass{
    public $prop1 = "I'm a class property!";
}
$obj = new MyClass;
echo $obj->prop1; // Output the property   
?>

I understand with $obj you're accessing $prop1, but what's happening in CakePHP when there's something like $obj->SomeModel->action()?

If possible could you modify that little OOP example to mimic that of CakePHP?

  • 写回答

3条回答 默认 最新

  • dongzhenshen7435 2013-08-13 14:43
    关注

    In your example, $this->loadmodel('Other') populates $this->Other with the model object you asked for. So you can treat it as a typical object (call methods, access properties, etc.). You could even do this:

    $this->loadmodel('Other');
    $other = $this->Other;
    $other->find('all');
    

    $other is assigned a reference to $this->Other, so they will both act exactly the same.

    As for chaining, let's say that $this->Other->find('all') returns another object of the type ResultSet, and the ResultSet class has the method getNumResults(). Chaining means you could do something like this:

    echo $this->Other->find('all')->getNumResults();
    

    As long as each method you're calling in the chain returns another object, you can keep calling the methods on that object.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法