class ContentController extends Controller
public function actionView($page) {
$content = FETCH CONTENT FROM DB WHERE CONTENT NAME = $page;
DISPLAY $content;
}
}
then you just add routing in main.php:
'components'=>array(
...
'urlManager'=>array(
...
'rules'=>array(
'site/<page:[\w\-]+>'=>'content/view',
...
//default rules go here
),
),
there is one drawback - with rules like this you cannot have ‘site’ controller because every request to ‘site/XXXXXX’ will be redirected to ‘content/view’ controller/action. You can change SiteController to IndexController or StartController, or change the rules to (for example) ‘cms/<page:[\w\-]+>’=>‘content/view’ which will map every request to ‘cms/XXXXXX’ to content/view and XXXXXX will be passed as ‘page’ param.
$page would be something that is identified in the url GET. So if you went to the url http://localhost/content/view/3, the controller action would use the 3 to fetch the desired content from db.
I know this thread was started some time ago but it could still prove useful for someone.
This is a valid question!
This doesn’t really make sense! $page should not carry the id whatsoever!
The setup should not be so different from normal CRUD except there is only 1 particular controller handling more than just 1 page/table/object with all their actions.
To avoid hiccups with the SiteController that comes with Yii by default, it would be much easier to call the new controller that handles the dynamic content something else but “Site” unless you really want “site” to be part of the URL. I would call this controller simply “ContentController”, “PageController” or “ViewController”. Anything but Sue Site! However, lets stick to SiteController.php just for now.
[*]/protected/components/Controller.php
class Controller extends CController
{
public $layout=...
public $menu=...
...
/**
* @var string dynamic params
* assign these params in the global action and have them
* easily accessible throughout the controller, all layouts and views
* and there's no more need to pass them from action to action, and view to view
*/
public $dynPage='';
public $dynAction='';
public $dynID='';
}
[*]/protected/controllers/SiteController.php
public function actionIndex($page, $action='index', $id=null)
{
$this->dynPage=$page;
$this->dynAction=$action;
$this->dynID=$id;
//do some exciting stuff here
//you can easily call different actions based on params (use switch/case) and keep your code structured
$this->render('view', array(
));
}
[/list]
Here’s an example to demonstrate how useful these global vars can be.
Keep in mind Yii’s controller id will always be “site” in this scenario but every once in a while you still need to know where you exactly are.
Another situation where these global vars are useful is in the navigation menu when you need to know which link is active or not. This way it’s really easy to have parent links active as well.