View Cells

View Cells allow you to insert HTML that is generated outside of your controller. It simply calls the specifiedclass and method, which must return a string of valid HTML. This method could be in any callable method, found in any classthat the autoloader can locate. The only restriction is that the class can not have any constructor parameters.This is intended to be used within views, and is a great aid to modularizing your code.

  1. <?= view_cell('\App\Libraries\Blog::recentPosts') ?>

In this example, the class App\Libraries\Blog is loaded, and the method recentPosts() is run. The methodmust return the generated HTML as a string. The method can be either a static method or not. Either way works.

Cell Parameters

You can further refine the call by passing a list of parameters in the second parameter to the method. The values passedcan be an array of key/value pairs, or a comma-separated string of key/value pairs:

  1. // Passing Parameter Array
  2. <?= view_cell('\App\Libraries\Blog::recentPosts', ['category' => 'codeigniter', 'limit' => 5]) ?>
  3.  
  4. // Passing Parameter String
  5. <?= view_cell('\App\Libraries\Blog::recentPosts', 'category=codeigniter, limit=5') ?>
  6.  
  7. public function recentPosts(array $params=[])
  8. {
  9. $posts = $this->blogModel->where('category', $params['category'])
  10. ->orderBy('published_on', 'desc')
  11. ->limit($params['limit'])
  12. ->get();
  13.  
  14. return view('recentPosts', ['posts' => $posts]);
  15. }

Additionally, you can use parameter names that match the parameter variables in the method for better readability.When you use it this way, all of the parameters must always be specified in the view cell call:

  1. <?= view_cell('\App\Libraries\Blog::recentPosts', 'category=codeigniter, limit=5') ?>
  2.  
  3. public function recentPosts(int $limit, string $category)
  4. {
  5. $posts = $this->blogModel->where('category', $category)
  6. ->orderBy('published_on', 'desc')
  7. ->limit($limit)
  8. ->get();
  9.  
  10. return view('recentPosts', ['posts' => $posts]);
  11. }

Cell Caching

You can cache the results of the view cell call by passing the number of seconds to cache the data for as thethird parameter. This will use the currently configured cache engine.

  1. // Cache the view for 5 minutes
  2. <?= view_cell('\App\Libraries\Blog::recentPosts', 'limit=5', 300) ?>

You can provide a custom name to use instead of the auto-generated one if you like, by passing the new nameas the fourth parameter:

  1. // Cache the view for 5 minutes
  2. <?= view_cell('\App\Libraries\Blog::recentPosts', 'limit=5', 300, 'newcacheid') ?>