Cakephp Filter gotcha for rails folks

February 16th, 2009

Usually in Rails, if you specify a before_filter in the base controller ‘ApplicationController’ (in application.rb), every other controller in that app inherits that filter, so that even if you specify a before_filter in another controller … the filter in application.rb always runs
Example:

class ApplicationController < ActionController::Base
   before_filter :check_login
end
class UploadsController < ApplicationController
    before_filter :get_data
end

The :check_login method is always run even though UploadsController specifies another before_filter.
(You can stop this behavior by specifying a skip_before_filter :check_login in the Uploads Controller)

However if you take this mindset with you to cakephp you’re in for a frustrating time. Because if you do something like this like this …

class AppController extends Controller{
    function beforeFilter(){
        if($this->Session->read('authenticated') != 'true'):
            $this->redirect('/login');
       endif;
    }
}
class UploadsController extends AppController{
    function beforeFilter(){
        $this->set('file_categories', $this->FileCategory->find('list', array('order' => 'name')));
    }
}

… you’re going to be left wondering why your very hastily thrown together authentication scheme, doesn’t work on the Uploads controller :\

Because the beforeFilter specified in each controller completely *overrides* the one from its parent (in php Object oriented programming, methods in child classes override the matching method in the parent), what you have to do *in PHP* is call the beforeFilter of the parent controller, first, before doing what you want to do.

So instead of the above, you do this …(note the emphasis)

class UploadsController extends AppController{
function beforeFilter(){
   parent::beforeFilter();
        $this->set('file_categories', $this->FileCategory->find('list', array('order' => 'name')));
   }
}

Entry Filed under: cakephp, ruby on rails

Leave a Comment

Required

Required, hidden

Some HTML allowed:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">

Trackback this post  |  Subscribe to the comments via RSS Feed


Calendar

February 2012
S M T W T F S
« May    
 1234
567891011
12131415161718
19202122232425
26272829  

I recommend

Linode VPS's for Rails hosting

Heroku for mindless Rails hosting

Site 5 for shared Rails hosting and all round great service

Most Recent Posts

Categories