上一篇已經介紹開發環境的搭建,這篇將從項目實戰開發,一步一步瞭解laravel架構。首先我們來瞭解下laravel架構的模型(Models)
在開發mvc項目時,models都是第一步。
下面就從建模開始。
1.實體關聯圖,
由於不知道php有什麼好的建模工具,這裡我用的vs ado.net實體模型資料建模
下面開始laravel編碼,編碼之前首先得設定資料庫串連,在app/config/database.php檔案
'mysql' => array( 'driver' => 'mysql', 'read' => array( 'host' => '127.0.0.1:3306', ), 'write' => array( 'host' => '127.0.0.1:3306' ), 'database' => 'test', 'username' => 'root', 'password' => 'root', 'charset' => 'utf8', 'collation' => 'utf8_unicode_ci', 'prefix' => '', ),
配置好之後,需要用到artisan工具,這是一個php命令工具在laravel目錄中
首先需要要通過artisan建立一個遷移 migrate ,這點和asp.net mvc幾乎是一模一樣
在laravel目錄中 shfit+右鍵開啟命令視窗 輸入artisan migrate:make create_XXXX會在app/database/migrations檔案下產生一個帶時間戳記首碼的遷移檔案
代碼:
<?php use Illuminate\Database\Schema\Blueprint;use Illuminate\Database\Migrations\Migration; class CreateTablenameTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { } /** * Reverse the migrations. * * @return void */ public function down() { } }
看到這裡有entityframework 遷移經驗的基本上發現這是出奇的相似啊。
接下來就是建立我們的實體結構,laravel 的結構產生器可以參考http://www.php.cn/
<?phpuse Illuminate\Database\Schema\Blueprint;use Illuminate\Database\Migrations\Migration;class CreateTablenameTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('posts', function(Blueprint $table) { $table->increments('id'); $table->unsignedInteger('user_id'); $table->string('title'); $table->string('read_more'); $table->text('content'); $table->unsignedInteger('comment_count'); $table->timestamps(); }); Schema::create('comments', function(Blueprint $table) { $table->increments('id'); $table->unsignedInteger('post_id'); $table->string('commenter'); $table->string('email'); $table->text('comment'); $table->boolean('approved'); $table->timestamps(); }); Schema::table('users', function (Blueprint $table) { $table->create(); $table->increments('id'); $table->string('username'); $table->string('password'); $table->string('email'); $table->string('remember_token', 100)->nullable(); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('posts'); Schema::drop('comments'); Schema::drop('users'); }}
繼續在上面的命令視窗輸入php artisan migrate 將執行遷移