简体   繁体   中英

Access model from /protected/config/main.php

I want to change a top menu in /protected/views/layouts/main.php so that it is stored in the database. I think to make it so: in /protected/config/main.php add in the array that returns from there an array of menu items:

return array(
    'basePath' => dirname(__FILE__) . DIRECTORY_SEPARATOR . '..',
    'name' => 'My Web Application',
    'preload' => array('log'),
    'menu' => array(
        array('label' => 'Home', 'url' => array('/site/index')),
        array('label' => 'About', 'url' => array('/site/page')),
        array('label' => 'Contact', 'url' => array('/site/contact'))
    ),

But menu items should be taken from database like objects of Menu model class. The question that interests me is how I can access model from /protected/config/main.php. If I write in /protected/config/main.php something like

$types = PageType::model()->findAll();

where PageType is existing model class, I get an error:

Warning: include(PageType.php) [function.include]: failed to open stream: No such file or directory in Z:\\home\\localhost\\www\\yii-1.1.16.bca042\\framework\\YiiBase.php on line 432

Warning: include() [function.include]: Failed opening 'PageType.php' for inclusion (include_path='.;/usr/local/php5/PEAR') in Z:\\home\\localhost\\www\\yii-1.1.16.bca042\\framework\\YiiBase.php on line 432

Fatal error: Class 'PageType' not found in Z:\\home\\localhost\\www\\mycms\\protected\\config\\main.php on line 8

I don't want to connect to the database directly from this script.

All done. I do it with using component instead of /config/main.php

I am just created in /protected/components/ directory a component class

class MainMenu extends CComponent {

private $items;

public function getItems() {
    $types=MainMenuItem::model()->findAll();
    return $types;
}

and used this component in /protected/views/layouts/main.php

$mainMenu = new MainMenu();
$itemsModel = $mainMenu->items;
$items = array();
foreach ($itemsModel as $m) {
    $label = $m->label;
    $url = $m->url;
    if (!empty($m->visible) && $m->visible == 'isGuest' && !Yii::app()->user->isGuest 
        || !empty($m->visible) && $m->visible != 'isGuest' && Yii::app()->user->isGuest) 
        continue;
    $item = array('label'=>$label . ($label == 'Logout' ? '('.Yii::app()->user->name.')' : ''), 'url'=>array($url));
    $items[] = $item;
}
$this->widget('zii.widgets.CMenu',array('items'=>$items));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM