Tuesday, July 3, 2012

Generating URLs by path in YII

Yii allows you not only to route your URLs to different controller actions but also to generate a
URL by specifying a proper internal route and its parameters. This is really useful because you
can focus on internal routes while developing your application and care about real URLs only
before going live.
1. Create a fresh Yii application using yiic webapp as described in the official guide
and find your protected/config/main.php. Replace rules array as follows:
// application components
'components'=>array(

// uncomment the following to enable URLs in path-format
/*
'urlManager'=>array(
'urlFormat'=>'path',
'rules'=>array(
'<alias:about>' => 'website/page',
'page/about/<alias:authors>' => 'website/page',
'page/<alias>' => 'website/page',
),
2. In your protected/controllers, create WebsiteController with the following
code inside:
class WebsiteController extends CController
{
public function actionIndex()
{
echo "index";
}
public function actionPage($alias)
{
echo "Page is $alias.";
}
}
This is our application controller that we are going to generate custom URLs for.
3. Configure your application server to use clean URLs. If you are using Apache with
mod_rewrite and AllowOverride turned on, then you should add the following
lines to the .htaccess file under your webroot folder:
Options +FollowSymLinks
IndexIgnore */*
RewriteEngine on
# if a directory or a file exists, use it directly
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# otherwise forward it to index.php
RewriteRule . index.php

No comments:

Post a Comment