Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cakephp beforeFilter vs constructor

Tags:

php

cakephp

I am new to cakephp. I found a largely used method

beforeFilter() 

My question is, how it's differ from a class constructor? What if i called

parent::beforeFilter();

from constructor instead of beforeFilter(); I just want to know what if i write the same code in

public function __construct() {
   // Code here
} 

instead of

public function beforeFilter() {
}

Thanks

like image 302
Dhinta Avatar asked Jul 26 '13 11:07

Dhinta


2 Answers

construct() is for construction, to load things you need.

__construct( ) public Constructor

Parameters: ComponentCollection $collection A ComponentCollection this component can use to lazy load its components

http://api.cakephp.org/2.3/class-Component.html#___construct


beforeFilter() executes functions that you NEED to be executed before any other action

Controller::beforeFilter() This function is executed before every action in the controller. It’s a handy place to check for an active session or inspect user permissions.

http://api.cakephp.org/2.3/class-Controller.html#_beforeFilter

Called before the controller action. You can use this method to configure and customize components or perform logic that needs to happen before each controller action.

Note: The beforeFilter() method will be called for missing actions, and scaffolded actions.

http://book.cakephp.org/2.0/en/controllers.html#request-life-cycle-callbacks

Usually you will not need a constructor as, when following CakePHP conventions there are only very few scenarios where you actually have no other option than to "force" loading something manually...

like image 166
pudelhund Avatar answered Sep 20 '22 13:09

pudelhund


You can find some relevant definitions from the official CakePHP documentation at https://book.cakephp.org/1.2/en/The-Manual/Developing-with-CakePHP/Controllers.html#the-app-controller:

"Callbacks: CakePHP controllers come fitted with callbacks you can use to insert logic just before or after controller actions are rendered. beforeFilter(): This function is executed before every action in the controller. It’s a handy place to check for an active session or inspect user permissions."

like image 35
Jaime Montoya Avatar answered Sep 20 '22 13:09

Jaime Montoya