views:

23

answers:

2

Hi all,

I am learning cakePHP 1.26.
A question came across my mind when I was creating a function in a Controller.
How do I maximize the usability of a self-defined function in CakePHP.

Here is my sample code:

function hello($id=null){

       $IfLoggedIn=$this->Session->check('user');

       if($IfLoggedIn){
        //search the database
        //$result=doing something from the search results
        $this->set('userInfo',$result);
        return "2";

       else if(!$IfLoggedIn && $id!=null){
       return "1";
        }

       else if($sid==null){
       return "0";
        }
}

and then in a .ctp file, I will make use of this function:

$u = $this->requestAction('../hello'); 
if($u==2){
echo "welcome back, my friend";
}
else{
echo "Hello World";

Please advise.

+1  A: 

It seems for me that you can do the job easier. You do not need that method in your controller. You can access anything stored in the session by using Session helper:

if($session->read('user')){
    echo "welcome back, my friend";
}else{
    echo "Hello World";
}
bancer
+1  A: 

Avoid the use of $this->requestAction() - hello() should be called from the view action and the result passed as a view variable.

Reusability is managed on a cascading system - on the controller it may be accessed by any method on the same controller. On app_controller it can be accessed from any controller. The same principle applies if it is data related - it goes on the model or app_model.

By applying the principles of MVC and OO properly, you're already doing things optimally.

Leo