I'm working on a web application, using the CAKEPHP framework. Herefor i need to request one variable on multiple pages (all pages have different controllers). it is oubvious that i get a 开发者_如何学Pythonerror on several pages, since the variable isn't declared in all the different controllers.
Is there a workaround for this? i've already tried the app:: import to import a controller in another controller, but this doens't seem to work (still get a undefined variable error).
Thnx for your cooperation!
Regards, Simon
Duplicate question, but I think it's phrased a bit better so I'll paste my answer here:
Standing on the shoulders of deceze's comment and DavidYell's answer, I think they've managed to scratch out a decent view of what you're trying to get to. Maybe. So with that loose understanding of what you're seeing and what you have...
By default, the
PagesController::display()
method generates the homepage view (home.ctp
). I suspect that this is what you're talking about. That said, the variable you're setting in a method of yourSectionsController
won't be available to your homepage which is created by a different method in a different controller. If you want a variable available to all views there are several things you can do:
- You can set the variable in your
config/core.php
file (not generally recommended)- You can set it in
config/bootstrap.php
if it's a constant. By that, I mean that it's a value you're going to hard code, not something dynamically generated. Whether you create the variable as a constant doesn't matter.- You can set in in your
AppController
in abeforeFilter()
orbeforeRender()
method. All of your custom controllers (assuming you've followed protocol) inherit from theAppController
. If you choose this path, make a copy ofcake/libs/controller/app_controller.php
and place it in yourapp/
directory.Those are the ways that I think will best meet your needs as I understand them.
You can use the Configure.write... more info here
More on configure class
One way to make sure that the variable is available on all pages is to define it on the front controller (normally index.php
) or any other always included file (such as global configs), another option might be to use the $_SESSION
super global.
You can youse the beforeRender()
or beforeFilter()
callback methods from your AppController. :)
These'll be called on every page request. :)
If you to access a value from different controllers, you will need to save that value into a database record so it can be accessed by the different controller methods. Each controller call exists in its own context and can only share data that is stored external to the scripts.
In situations like this, I've created a preferences table (with fields like, id, name and value). Then add a $uses value to the app_controller to make it available to all controllers. Finally, just grab it with a find call. (ie. $foo = $this->Preferences->find( 'first', array('conditions'=>array('name'='foo')));
精彩评论