简体   繁体   中英

CakePHP Fatal error: Call to a member function check() on a non-object?

Hey everyone I am getting this error

"Fatal error: Call to a member function check() on a non-object in C:\\xampp\\htdocs\\job_portal_cakephp\\app\\Controller\\Component\\SeekerSessionComponent.php on line 4"

Component Code(SeekerSessionComponent.php)

<?php
class SeekerSessionComponent extends Component{
    function session_check(){
        if(!$this->Session->check("id")){
            die;
            $this->redirect(array("controller"=>"Pages","action"=>"login"));
        }
    }
}
?>

Controller Code(PagesController.php)

App::uses('AppController', 'Controller');


class PagesController extends AppController {
public $name = 'Pages';


public $helpers = array('Html', 'Session');


public $uses = array("Job","Page","Seeker","Skill");

public $components = array("Sanitize","SeekerSession");

public function index(){
    $this->SeekerSession->session_check();
    $this->layout = "first_layout";
    $jobs = $this->Job->query();
    $this->set(compact("jobs"));
}
}

I have Pages controller which has index function which uses SeekerSessionComponent to check if session with variable "id" exists or not.

based on link:- https://book.cakephp.org/2.0/en/controllers/components.html#creating-a-component

You forgot to add App::uses(Component, Controller); in your component class code.So it should be like below:-

App::uses('Component', 'Controller');//missed

class SeekerSessionComponent extends Component {
   public $components = array('Session');// missed
    public function session_check(){
        if($this->Session->check("id")){ // if id exist
            return true; //return true
        }
    }
}

Note:-

component function must be public .

Also

die;$this->redirect(array("controller"=>"Pages","action"=>"login")); it doesn't seems correct code, you need to return something not stopping execution or redirecting to any page .

Check by printing $this->Session in 4th line of your code mentioned above. This is returning a null value means it does not return any object and then your code tries to call check() function on null.

 <?php
    class SeekerSessionComponent extends Component{
        function session_check(){
            echo "<pre>";
            print_r($this->Session);
            die;
            /*if(!$this->Session->check("id")){
                die;
                $this->redirect(array("controller"=>"Pages","action"=>"login"));
            }*/
        }
    }
    ?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM