第三章初識laravel,helloWorld的MVC實現
一、簡單粗暴的laravel4部曲
Laravel的程序主幹,對我們使用者來說,主要就是4步:
第一步:綁定路由
第二步:寫controller
第三步:寫model
第四步:寫view
本章教程將嚴格按照這四步爲你演示基於mvc的“helloworld”,讓你瞭解laravel程序的一般開發流程。
二,基於laravel的hello world實現:
1、綁定路由
打開phpstorm,打開“app\Http\routes.php”,文件,添加以下代碼:
Route::get('hello','helloController@index');
2、寫model
右鍵“app\Http”,新建一個文件夾“model”,然後在該文件夾下新建一個“hello.php”文件。
在hello.php中添加以下代碼:
<?php namespaceApp\Http\model;
useIlluminate\Database\Eloquent\Model;
class hello extends Model {
public function index() {
return ['msg' => 'hello World!'];
}
}
3、寫controller
右鍵“app\Http\controller”文件夾,“新建”,“文件”,輸入文件名“helloController.php”,點“確定”
然後在文件中“helloController.php”中輸入以下代碼:
<?php namespaceApp\Http\Controllers;
use App\Http\model\hello;
class helloController extendsController {
protected $model;
public function __construct(hello $hello) {
$this->model = $hello;
}
public function index() {
returnview('hello',$this->model->index());
}
}
4、寫view
在“resources\views”文件夾下,新建一個“hello.blade.php”文件,輸入以下代碼:
{{$msg}}
5、打開瀏覽器,輸入網址
好了,不出意外,你應該能看到如下界面:
恭喜你,基於laravel的hello world 寫好了。完整的mvc實現。
三、結語:
本章所示的就是laravel的mvc完整開發流程,我們的後續開發都離不開這4步,當然,如果你不走MVC,會更簡單。閱讀至此,你會發現,你未對laravel進行任何配置,是的,laravel就是這麼神奇,當天下第一框架thinkPHP還在rewrite rule時,你的helloword已經寫好了。清晰簡單的url,高度自由的文檔結構(laravel的MVC目錄都是可以更改的,這將在以後的介紹中說明)。