Revision #3 was created by qiang on Apr 12, 2011, 1:06:08 AM.
Added "refactoring the code" section
Content
[...]
So what are new stuff here?
* First, instead of saving a string as flash message, we save an array of data that will persist to the next page request.
* Second, we use the action code to control which view to render. The code conforms better to the MVC pattern.
## Refactoring the code
If an application needs to display different success pages in different actions, we may refactor the above code so that the usage is even simpler and more DRY.
First in the [base controller class](http://www.yiiframework.com/wiki/121/extending-common-classes-to-allow-better-customization), define the following method:
```php
/**
* Renders a success view.
* Note that this method will redirect the browser to the 'site/success' route
* which will then render the specified success view.
* @param string $view the view name. It can be a view relative to
* the current controller or an absolute view (starting with '/')
* @param array $data the data to be passed to the view.
*/
public function success($view, $data=array())
{
if($view[0]!=='/') // relative to current controller
$view = '/' . $this->id . '/' . $view;
$data['_view_'] = $view;
Yii::app()->user->setFlash('_success_', $data);
$this->redirect(array('site/success'));
}
```
Then, in the `SiteController` class, define the following `success` action:
```php
/**
* Displays a success page.
* The success page content is specified via the flash data '_success_'
* which is generated by {@link Controller::success()} method.
* If the flash data does not exist, it will redirect the browser to the homepage.
*/
public function actionSuccess()
{
if (!Yii::app()->user->hasFlash('_success_'))
$this->redirect(Yii::app()->homeUrl);
$data = Yii::app()->user->getFlash('_success_');
$view = $data['_view_'];
unset($data['_view_']);
$this->render($view, $data);
}
```
Now, the previous `actionRegister()` method can be greatly simplified: