[Laravel] LAMP+Laravel 學習筆記-ORM-Eloquent

Laravel Database
1.DB連線設定
2.建立Model(對應實體table)
3.Model的專案分層(Service-->Repository)
4.Repository的CRUD


#名詞說明
Service =Business Logical Layer
Reposiotry =Data Access Layer

  • DB連線設定
    設定mysql帳號密碼, 修改.env
DB_CONNECTION=mysql
DB_HOST=localhost
DB_PORT=3306
DB_DATABASE=testDB
DB_USERNAME=testID
DB_PASSWORD=testPassword


使用php artisan make:model 自動產生Model檔案

php artisan make:model blog\\Model\\Member
  • 產生 app/blog/Model/Member.php
<?php

namespace App\blog\Model;

use Illuminate\Database\Eloquent\Model;

class Member extends Model
{
   //手動指定table:,預設無此變數
    protected $table = 'member';
    //可被指定的屬性
    protected $fillable = array('username', 'nickname', 'email');
    //$fillable相反:不可被指定的屬性
    protected $guarded = array('userID', 'password');
}
  • Model的專案分層
    Controller ->Model  {{
         BusinessLogicLayer(Service)->DataAccessLayer(Repository) -->DB
    }}
     

不管專案大小,資料庫的CRUD 建議放在DA層
優點:
1.底層的資料存取可更換且不影響上層View/Controller/Service
   有效的強調了,Repository的主要工作
2.Service 業務邏輯封裝了所需的外部資源 (File,外部Servie, Other DB Source..)
  有效強調了"業務邏輯" 這個層次的 主要工作,並封裝底層實做
3.Service 與 Repository間的傳遞

  1. 統一傳遞物件:Class
  2. 宣告Class繼承Eloquent\Model
    Active Record 功能
    e.g: product::All()
    $product::where('id',3)


Controll Sample:home.php
主要呼叫Service, 並將資料,以陣列的格式 傳送給view
View('index',  [$bannerHomeTop: $bannerTop , $bannerHomeProducts:$bannerProducts]  );

<?php
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\blog\Service\BannerService;


class home extends Controller
{   
    protected $bannerService;
    public function __construct(){        
        $this->bannerService=new BannerService();
    }
    public function index()
    {  
        $bannersHomeTop=$this->bannerService->getBannerHomeTop();
        $bannersHomeProducts=$this->bannerService->getBannerHomeProducts();
        $data['bannersHomeTop']=$bannersHomeTop;
        $data['bannersHomeProducts']=$bannersHomeProducts;                
        return view('index',$data);
    }
}

View: /resources/views/index.blade.php

<html>
@foreach ($bannerHomeTop as $banner)
   <a href="{{banner->url}}" target="_blank" > 
   <img src="{{banner->img}}">
   </a>
@endforeach
</html>



Service : BannerSerivce.php
 

<?php
namespace App\lytbirdsnest\Service;
use App\lytbirdsnest\Repository\BannerRepository;

class BannerService
{
    protected $bannerRepository; //data access layer
    public function __construct()
    {
        $this->bannerRepository =new BannerRepository();        
    }


    public function getBannerHomeTop(){
        $bannersTop=$this->bannerRepository->getBannerByDataType('首頁_上');
        return $bannersTop;
    }
} 

 

  • Repository 的CRUD

Repository: BannerRepository
將$this->banner宣告為Model\Banner
可直接操作CRUD:
Create $banner->save();
Read:$this->banner->get();
Update:$banner->save();
Delete:$banner->forcedelete();

 

<?php
namespace App\blog\Repository;
use Illuminate\Database\Eloquent\Collection;
use App\blog\Model\Banner;

class BannerRepository
{
    protected $banner;
    public function __construct()
    {        
        $this->banner=new Banner();
    }

    //Create
    public function Create(Banner $banner)
    {
         $banner->save();                  
    }

    //Read
    public function getBannerByDataType($dataType)
    {
        //查詢
         return $this->banner
                 ->where('data_type','=',$dataType)
                 ->where('status','=','Y')
                 ->where('start_date','<=',date)
                 ->where('end_date','>=',date)
                 ->orderBy('sn','desc')
                 ->get();        
    }
    
    //Update
    public function Update(Banner $banner)
    { 
        $bannerToUpdate=$this->banner->find($banner->id);  
        $bannerToUpdate->UpdateDate=date();
        $bannerToUpdate->UpdateUser='sys';         
        //修改
         $banner->save();                  
    }

    //Delete
    public function Delete(Banner $banner)
    {   
         $bannerToDelete=$this->banner->find($banner->id);   
         //強迫刪除
         $bannerToDelete->forceDelete();                  
    }
}





 

 

參考:Laravel Eloquent ORM