我正在使用Yii,我是新手。我有一个默认的主布局文件.php我需要从数据库和 cookie 中提取一些数据。我写了 2 个函数:
public function getRegionId() {
if(isset(Yii::app()->request->cookies['region_id'])) {
$sk = Yii::app()->request->cookies['region_id']->value;
settype($sk,integer);
return $sk;
} else {
return 1;
}
}
public function regionId2region($id) {
if(empty($id) or gettype($id)!=='integer') {
return null;
} else {
$reg = Regions::model()->findAll(array(
'condition'=>"alive=1 AND id=".$id,
));
return $reg;
}
}
现在它在任何控制器中都不起作用。我的问题是:是否可以在布局文件中创建函数,或者是否有办法将数据传递到布局文件(以便它显示在所有控制器中)?
将方法移动到区域模型中并使其成为静态。还是创建帮助程序类?仅包含静态方法。
class RegionHelper {
public static function getRegionId() {
if(isset(Yii::app()->request->cookies['region_id'])) {
return (int)$Yii::app()->request->cookies['region_id']->value;
}
return 1;
}
public static function regionId2region($id) {
if(empty($id) or gettype($id)!=='integer') {
return null;
} else {
$reg = Regions::model()->findAll(array(
'condition'=>"alive=1 AND id=".$id,
));
return $reg;
}
}
}
控制器中使用BeforeAction
,如下所示:
protected function beforeAction($action) {
//Define your variable here:
public $yourVaribale;
//do your logic and assign any value to variable
}
现在,您可以在视图文件中使用此变量:
视图:
<h1><?php echo $this->yourVariable; ?></h1>
如果函数位于调用视图的控制器中,则可以使用 $this 引用来访问该函数。请注意函数的公共访问。
class UserController extends Controller
{
// :
// :
public function fullName($a,$b) {
return $a.' '.$b;
}
}
。在您看来...
<h1>Test for <?php echo $this->fullName('Tom', 'Jones'); ?></h1>
如果函数位于模型中,则有几种选择。
class User extends Activerecord
{
// :
// :
public function fullName($a,$b) {
return $a.' '.$b;
}
}
您可以通过渲染函数传递模型,
class UserController extends Controller
{
// :
// :
public function actionDisplayView {
$userModel = User::model()->findByPK(1);
$this->render('user_view', array('model' => $model));
}
}
并直接在视图中调用函数。
< h1 >Test for <?php echo $model->fullName('Tom', 'Jones'); ?>< / h1 >
或者,如果未传递函数,则可以在视图(或帮助程序类)中调用该函数。观察示波器。
class User extends Activerecord
{
// :
// :
// NOTE: You won't have access to $this.
static public function fullName($a,$b) {
return $a.' '.$b;
}
}
并在视图中
< h1 >Test for <?php echo User::fullName('Tom', 'Jones'); ?>< /h1 >