当前位置: 动力学知识库 > 问答 > 编程问答 >

php - undersanding CakePHP's controller

问题描述:

I am going through the CakePHP's beginner tutorial and I have a question:

In the blog tutorial, the have created the following function in the Controller

public function index() {

$this->set('posts', $this->Post->find('all'));

}

I'm trying to better understand what this means, specifically

$this->Post->find('all')

This is a reference to the Controller object's Post object and then calling its find function.

Is this Post object a linkedList (or some other data structure) of Post objects? That seems to be the only way it makes sense but I want to make sure. I am used to OOP in Java and a newbie in OOP in PHP and think I might be missing some pieces.

网友答案:

Your Model controls the database access. So, when you want data from your database, in your Controller, you need to use the Model to retrieve it.

$this->Post->find('all');

tells the 'Post' Model to retrieve all posts.

Best practice is actually to not use the find() method from your Controller at all, and instead, call a custom method created in your Model. For example:

//inside PostsController
$posts = $this->Post->getPosts();

//inside Post Model
public function getPosts() {
    return $this->find('all');
}

This usually gets a lot more complicated as you add conditions, limits, orders...etc, but done this way, it more closely follows the MVC, the M (Model) is what does all the data-retrieval. (and also makes your code cleaner, so anytime you want to update the find, you only have to do it in one place, and not across many controllers)

网友答案:

It call a method find of your model Post. your model have find because it extend a AppModel.

   App::uses('AppModel', 'Model');
  class Post extends AppModel {
        public $name = 'Post';
    }

and return ll be something like this

(its only example, it ll depend ur database and ur model post/user... etc)

Array
(
    [Post] => Array
        (
            [id] => 83
            [desc] => 'it is a test post'
            [user_id] => 2

        )

    [user] => Array
        (
            [id] => 2
            [name] => 'rafael'
            [phone] => '9999-000'
        )
)

and this array ll be disponible for your views acess in variable 'posts'.

分享给朋友:
您可能感兴趣的文章:
随机阅读: