本文基於Laravel 4.2編寫。php
Route::get('/helloworld', function() { return '<html><body>hello world</body></html>'; });
app/routes.phphtml
Route::get('/helloworld', function() { return View::make('helloworld'); }); app/views/helloworld.php <html> <body> hello world </body> </html>
app/routes.php(此次咱們的路由要先指向Controller,而後再由Controller返回View內容)laravel
Route::get('/helloworld', 'HelloworldController@say');數據庫
app/controllers/HelloworldController.php瀏覽器
<?php class HelloworldController extends BaseController { public function say() { $action = 'hello'; $name = 'kitty'; return View::make('hello.world', compact('action', 'name')); // hello.world表示hello目錄裏的world.php文件; 咱們傳入兩個變量$action和$name } }
app/views/hello/world.php(此次咱們放在一個子目錄裏,避免views目錄文件太多)app
<html> <body> {{$action}} {{$name}} </body> </html>
頁面將顯示「hello kitty」框架
app/routes.phpui
Route::get('/helloworld', 'HelloworldController@say'); app/controllers/HelloworldController.php <?php class HelloworldController extends BaseController { public function say() { $name = 'kitty'; $contacts = Contact::getContacts(); return View::make('hello.world', compact('name', 'contacts')); } }
app/models/Contact.php設計
<?php // 假設有個表contacts(uid, name, phone) class Contact extends Eloquent { public $timestamps = false; protected $primaryKey = 'uid'; static public function createContact($uid, $name, $phone) { // 這個方法只是演示Model可能有些什麼內容,並無實際調用。 $item = new Contact; $item->uid = $uid; $item->name = $name; $item->phone = $phone; $item->save(); return $item; } // 假設有兩行內容:(1, ‘kitty’, ‘800888’), (2, 'dingdong', '900999') static public function getContacts { return DB::table('contacts')->get(); } }
app/views/hello/world.blade.php(因爲須要使用循環等超越HTML語法的功能,咱們須要使用blade模板語言,文件名裏須要添加blade部分)code
<html> <body> @foreach ($contacts as $contact) {{ $contact->name }}’s number is {{ $contact->phone }}, @endforeach </body> </html>
頁面將顯示「kitty's number is 800888, dingdong's number is 900999,」
模板語言更多語法可參考:https://laravel.com/docs/4.2/templates
至此,MVC(Model-View-Controller)的框架進化完成。