Cakephp Filter gotcha for rails folks

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')));
   }
}