2

I am using CakePHP 2.8.3 and trying to use this component into my controller but I am getting this error, Does anybody experienced same please help.

Fatal Error Error: Call to a member function header() on a non-object File: /mnt/hgfs/Projects/dev_kp/lib/Cake/Controller/Controller.php
Line: 779 Notice: If you want to customize this error message, create

app/View/Errors/fatal_error.ctp

//Controller
    <?php

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

    class UsersController extends AppController
    {
        public $name = 'Users';
        public $components = array('UserAuth');
        public $uses = array('User');

        public function dashboard()
        {
            echo $this->UserAuth->ValidateUser();
        }
    }
    ?>

    //Component
    <?php

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

    class UserAuthComponent extends Component
    {

        public function ValidateUser()
        {
           if(isset($_SESSION["USER_VALIDATE"]))
           {
              if($_SESSION["USER_VALIDATE"] == TRUE)
                 return TRUE;
           }
           else
           {
              $direct = new AppController();
              $direct->redirect(array('controller' => 'users', 'action' => 'login'));
            }
         }
     }
    ?>
Keyur Padalia
  • 2,077
  • 3
  • 28
  • 55

1 Answers1

1

First things first

CakePHP ships with an authentication layer, there's little to no need to implement your own. If you need custom authentication, then you should implement it using custom authentication objects, see

That being said

What you are doing there is not how CakePHP works, you do not instantiate controllers manually, also you do not access superglobals like $_SESSION directly, instead you use the abstracted interfaces that CakePHP provides.

Before throwing code together, read the docs and make sure sure that you understand the APIs that you are working with.

As you can see, components do receive a reference of the controller on which they are being used in every callback, so if you need to access controller functionality, you use that reference. If you need to use it at a later point, store it in a property, like

protected $_controller = null;

public function initialize(Controller $controller) {
    $this->_controller = $controller;
}

public function ValidateUser() {
    // ...
    $this->_controller->redirect(/* ... */);
}

The session can easily be accessed via the session component that you can include in your custom component, like

public $components = array('Session');

public function ValidateUser() {
    // ...
    $value = $this->Session->read('USER_VALIDATE');
}
ndm
  • 59,784
  • 9
  • 71
  • 110