Import Controller + Session = Fatal error

Hello,

I have the following issue :

I have 2 controllers : Controller A and Controller B .

I need to use some logic( call a method ) in Controller A that is defined in Controller B.

Inside Controller A I use :

 
App::Import('Controller','B');
$controllerB = new BController();
$controllerB->someMethod();

In controller B I have :


public function someMethod()
{
return $this->Session->read('somevar');
}

The problem is that when someMethod is called in controller A I receive a fatal error:

Notice (8): Undefined property: BController::$Session

and

Fatal error: Call to a member function someMethod() on a non-object

I have specified var $components = array('Session') and I tried a lot of other solutions but it just wont work if I use the session object inside a class that has been imported.

Can you guys please give me a hand ?

I appreciate,

Dragos

Asked by Aussie, on 20/2/12

1 Answer

you should never ever use a controller inside another controller!

if you are in need to do that it is a clear signal that you are doing something awefully wrong here.

put that code you need in both controllers inside a model method, a component, or even a lib and then just call it from each of those two controller actions.

Answered by euromarkon 21/2/12

Thank you for the reply .

I know is bad practice , but there are cases where it would be very useful .

You are asked to develop a future , you create the controller for it and it's fine ...than the client comes and says he wants the same logic you developed earlier to appear on a new page.

Because you did not know that from the beginning you are a trapped ... you cannot call that controller logic in the new page because it will fail...and to move the logic inside a lib , will be time consuming and the original controller will have to be re-tested and so on.

Aussie - on 21/2/12

<< comments | comments >>
<< previous next >>

Your Answer

You can use Creole Wiki Syntax to format your text.

Rating

0

Viewed

244 times

Last Activity

on 21/2/12