本文基于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)的框架进化完成。