简体   繁体   中英

Cake PHP multiple view pages have access to the same variables

I'm doing the blog tutorial (CakePHP 2.4.1) and have a question.

What is the reasoning ( and why) does the index.ctp page require me to loop through the $posts variable to get data but the view.ctp file lets me just grab $post without looping? I deleted the following action in PostController.php and still could render the view.ctp file so I figure the two are not connected.

 public function index() {
    $this->set('posts', $this->Post->find('all'));
}

You're setting post in both of the controller's functions:

index()

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

view()

$post = $this->Post->findById($id);
$this->set('post', $post);

It would be odd if you weren't able to access the variables, but it seems everything is functioning as normal in your example

Edit:

You loop through the array in the index because you have multiple posts inside of an array. And in the view you're setting only a singular array containing one post so there is no need to loop through anything, you're able to grab the elements directly.

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

This will return an array of posts - notice the find('all')

    $this->set('post', $this->Post->findById($id));

This will return a single post by the passed $id parameter.

The reason you have to loop through $posts is because its an array (returned by the find all), where $post is just a single post returned by findById)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM