0

I've got a Component that is used by many controllers, and I was wondering if there is a way to access the Controller object from the Component without having to pass it into the Component.

For example I'm currently passing in a reference to the controller into MyAuthComponent:

$this->Auth->isAuthenticated($this);

But, I'd rather be able to invoke this without having to pass the references if possible. Is this possible?

3 Answers 3

3

Component callbacks receive controller instance as a parameter. So using your component's startup() callback save the reference to component property and you can then use that in other methods of your component. Check the manual/api for the list of arguments startup() receives.

Sign up to request clarification or add additional context in comments.

Comments

1

Here is code example for @ADmad answere

class AuthComponent extends Component {    
    var $controller = null;
         /**
         * Startup component
         *
         * @param object $controller Instantiating controller
         * @access public
         */ 
        public function startup(Controller $controller) {        
            $this->controller = $controller;
        }
}

Comments

0

As per cakephp3.x guidelines using registry you can access current controller from within component.

$controller = $this->_registry->getController();

and you can access controller in any component callback methods using event objects mentioned below.

$controller = $event->getSubject();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.