Monday, March 16, 2009

Utilizing the AppController::beforeRender to Assign CakePHP's Controller Attributes

Monday, March 16, 2009
This may be a matter of preference, but I think it's a pain to assign CakePHP's controller attributes to all views in my controllers. So I always do this in my applications.

Add a $this->set into the AppController::beforeRender to always read $this->data.
class AppController extends Controller {
function beforeRender() {
 if (!isset($this->viewVars['data'])) {
  $this->set('data', $this->data);
 }
}
}
In your controller (any controller that extends the app controller), you don't have to assign $this->data any more.
class PostsController extends AppController {
function index() {
 $this->data = $this->paginate();
}
}
In this manner, you can also do something like the following:
function beforeRender() {
 if (!isset($this->viewVars['data'])) {
  $this->set('data', $this->data);
 }
 if (!isset($this->viewVars['modelClass'])) {
  $this->set('modelClass', $this->modelClass);
 }
}
Now, you can access them anywhere in views with $data and $modelClass.
<? if($data): ?>
<? pr($data)?>
<? endif; ?>

<? if($modelClass): ?>
<? pr($modelClass)?>
<? endif; ?>

0 comments:

Post a Comment

Please feel free to post your comment about this article.

 
JamNite ◄Design by Pocket, BlogBulk Blogger Templates