cakephp/cakephp — pull request #3216 by quickapps (2014-04-04 00:35:53+00:00)
Title: View Cells for #3052

Here is a proposal implementing View Cells. There still a few things to do yet, so please consider this as a preview. Let me know what you think :)

***

Conventions:

- Cell classes name must end with `Cell` word. e.g.: TagCloudCell.php
- Must extend the abstract class `\Cake\Cell\Cell`
- And implement the render() method. (Cake\Cell\RenderInterface)
- Cell's template must be located in `Template/Cell/` directory
- Template's name = underscored name of the class e.g.: `tag_cloud` for TagCloudCell class

Example:

// App/Cell/LatestNews.php
namespace App\Cell;

class LatestNews extends Cake\Cell\Cell {
public function render(array $options = []) {
$limit = empty($options['limit']) ? 5 : $options['limit'];
$category = empty($options['category']) ? [] : ['category' => $options['category']];
$this->loadModel('News');
$this->set('tags',
$this->News->find()
->where($category)
->limit($limit)
->all()
);
}
}

***

There is also a `Cake\Cell\CellTrait` for implementing cell() method on Controller and View.

CellTrait::cell() returns a Cell object, **cells are not rendered until they are echoed**. This allows us to save resources on some particular cases.

$news= $this->cell('LatestNews', ['limit' => 3]);
echo $news; // triggers rendering cycle (Template/Cell/latests_news.ctp)

$news = $this->cell('LatestNews', ['limit' => 5, 'category' => 'Music']);
$news = (string)$cell; // this aswell

Of course dot-notation is allowed for rendering plugin's cells:

$tags = $this->cell('Taxonomy.TagCloud', ['amount' => 20]);
echo $tags; // (Plugin/Taxonomy/Template/Cell/tag_cloud.ctp)

***

TODO:

- Cache
- View.before|afterRender ?
- MissingCellException ?
- Write some test cases
- Write decent docblocks, my english sucks

Best Regards!