Imagine a typical CakePHP application, in which a Controller passes various bits of data to开发者_开发技巧 the View using $this->set
in the typical way:
class ThingsController extends AppController {
function test() {
$this->set('someparam', 5);
}
}
If the corresponding View was to define and use a small helper function which outputs some HTML, is there any way to access that variable $some_param
from within the function? I would have thought you could just access it as a global variable, but it always come out with the value NULL
.
<?php
function helper_function() {
global $someparam;
echo var_dump($someparam); // Just prints NULL
}
?>
<h1>I am a View!</h1>
<?php helper_function(); ?>
To be honest, an even simpler use case is for the helper_function
to be able to access things like the $html
and $javascript
helpers.
In the situation you describe, you're going to be operating on the value after you've set it for the view. You may or may not be changing that value. Either way it could get confusing. It would be clearer - and make life easier when you've forgotten how this app works - to do something like
function test() {
$myVar = 5;
$this->helper_function($myVar);
$this->set('some_param', $myVar);
}
As for accessing the helper functions, you can do this and there are times when there doesn't seem to be an alternative, but it is best avoided wherever possible as it breaks MVC.
This:
<h1>I am a View!</h1>
<?php helper_function(); ?>
just isn't right (assuming you have written the function in the controller). I would be calling that function in the view's controller action and passing the result out as a variable. Just try to remember, use the controller to prepare data for the view. Use the view to display the data.
Why not write your own helper? That would appear to be the way to solve your problems.
The view isn't in the global scope, and $this->set()
doesn't make the variable available to the global scope.
If you want the variable available in helper_function()
, you should just pass it in as an argument:
function helper_function( $arg )
{
// Do stuff with $arg here
}
Accessing other helpers is something a custom helper can do:
class SomeHelper extends AppHelper
{
// Use the same syntax as the controller to add helpers to your custom helper
var $helpers = array('Html','Javascript','Form');
// Then in the methods, refer to these other helpers thus:
function helper_function( $arg )
{
$out = '';
$out .= $this->Html->div('class','text here');
$this->Javascript->codeBlock("some jQuery here",array('inline'=>false));
$out .= $this->Form->input('Model.fieldName',array('type'=>'hidden','value'=>$arg));
return $out;
}
}
use configure::read and write - sounds like they are some kind of configuration stuff in your app
this way you can access them anywhere you want
精彩评论