4

in a function I want to reach current controller:

$front = Zend_Controller_Front::getInstance();

this only gives a handler but not current controller.

I changed the code from function to inside of controller. and asked their origins both the handler I got from getInstance and this

var_dump(get_class($front), get_class($this));

I get:

string 'Zend_Controller_Front' (length=21)
string 'IndexController' (length=15)

How can I reach real initiated front controller?

I cant pass as a parameter, because this function is used trillion times.

nerkn
  • 1,867
  • 1
  • 20
  • 36
  • for quicness I defined a global variable, in IndexController init I set it with $this. – nerkn Dec 03 '10 at 13:06
  • Getting an instance of an action controller is generally not a great idea. If you need code that resides in your action controller available elsewhere in your application or library, that code should likely be in your library to begin with. The second answer by takeshin also states this. – Darryl E. Clarke Dec 03 '10 at 15:27
  • I need a variable defined in controller in a function that makes links.(href) Should I bind this function to a class? – nerkn Dec 03 '10 at 15:40
  • Any method in controller which is not an action should be probably marked as *protected*. Protected method in controllers are generally a sign, you should separate them in [action helper](http://framework.zend.com/manual/en/zend.controller.actionhelpers.html). – takeshin Dec 04 '10 at 19:43

2 Answers2

7
Zend_Controller_Front::getInstance()->getRequest()->getControllerName();
Alex Pliutau
  • 21,392
  • 27
  • 113
  • 143
1

Possible with:

$front = Zend_Controller_Front::getInstance()
$request = $front->getRequest();
$module = ucfirst($request->getModuleName());
$controller = ucfirst($request->getControllerName());

$instance = new $module . '_' . $controller . 'Controller';

In Action Helper:

$instance = $this->getActionController();

But, this probably means that's something wrong with your architecture.
You should move the common code you need to action helper, service or model.

takeshin
  • 49,108
  • 32
  • 120
  • 164
  • 1
    Of course, the first approach produces a second instance of the controller class, not the instance created within the dispatch loop. Right? In any case, as you note, needing a reference to the controller instance itself is probably indicative of some architecture issue. – David Weinraub Dec 04 '10 at 16:27