Laravel入門:MVC框架

本文基於Laravel 4.2編寫。php

  1. 路由Hello World 在app/routes.php裏面添加下面代碼,而後在瀏覽器裏訪問http://<laravel host prefix>/helloworld能夠見到結果。
Route::get('/helloworld', function() {
  return '<html><body>hello world</body></html>';
});
  1. 視圖(View) 理論上能夠把全部代碼都寫在app/routes.php裏面,可是這會令代碼難以維護。因而,咱們能夠把具體的頁面內容搬到視圖裏,讓路由文件簡短一些。

app/routes.phphtml

Route::get('/helloworld', function() {
  return View::make('helloworld');
});

app/views/helloworld.php

  
<html>
  <body>
    hello world
  </body>
</html>
  1. 控制器(Controller) 咱們寫的是動態網頁,頁面裏有變量,變量經過Controller傳入View。

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」框架

  1. 模型(Model) 隨着業務邏輯的複雜,Controller文件會變長很差維護,那麼咱們能夠把和數據庫查詢相關的邏輯分到模型層裏,甚至能夠安排一個擅長數據庫表設計和寫SQL的人專門負責這一層。

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)的框架進化完成。

相關文章
相關標籤/搜索