EllisLab/CodeIgniter — pull request #2650 by richardkmiller (2013-09-18 19:43:28+00:00)
Title: Autoload views by naming convention

## Autoloading views
This pull request autoloads views based on controller and action names. For example, a call to `/about/company` will attempt to autoload and render `/application/views/about/company.php`.

Your code like this:
```php
class About extends CI_Controller
{
public function company() {
$vars['company_name'] = "Acme, Inc.";
$this->load->view('about/company', $vars);
}
}
```

can be changed to this:
```php
class About extends CI_Controller
{
public function company() {
$vars['company_name'] = "Acme, Inc.";
return $vars;
}
}
```

## AJAX
The method can also be changed to emit JSON as an AJAX endpoint. If `__ajax == true` then no view will be loaded, and instead `$vars` will be JSON-encoded and echoed.
```php
class About extends CI_Controller
{
public function company() {
$vars['company_name'] = "Acme, Inc.";
$vars['__ajax'] = true;
return $vars; // echoes JSON; view not rendered
}
}
```
Alternatively, you can prefix the method name with `ajax_` for the same effect:
```php
class About extends CI_Controller
{
public function ajax_company() {
$vars['company_name'] = "Acme, Inc.";
return $vars; // echoes JSON; view not rendered
}
}
```
This allows for some interesting code sharing since methods can call other methods (sort of a poor man's HMVC):
```php
class About extends CI_Controller
{
public function ajax_company() {
$vars['company_name'] = "Acme, Inc.";
return $vars;
}
public function company() {
$vars = $this->ajax_company();
$vars['confidential'] = "Value needed in the template but not to be emitted as AJAX";
return $vars;
}
}
```
A call to `/about/ajax_company` will return JSON with the value `company_name`, while a call to `/about/company` will render `/views/about/company.php` with the values `company_name` and `confidential`.

## Functional Testing
Separating the rendering of views from the calling of controller methods also makes functional testing easier:
```php
class AboutTest extends PHPUnit_Framework_TestCase
{
public function test_company()
{
$about = new About();
$company = $about->company();
$this->assertEquals($company['company_name'], "Acme, Inc.");
}
}
```

## Layouts
This pull request also introduces the concept of *layouts*. Layouts provide common markup across multiple web pages, such as headers, footers, etc.

You would start by creating a layout, e.g. `/application/views/layouts/my_layout.php`
```php

Header

Footer

```

The above PHP code can then be rewritten to wrap the layout around the view:
```php
class About extends CI_Controller
{
public function company() {
$vars['layout'] = "my_layout";
$vars['company_name'] = "Acme, Inc.";
return $vars;
}
}
```