首頁  >  文章  >  後端開發  >  Laravel 5中的倉儲模式

Laravel 5中的倉儲模式

PHPz
PHPz原創
2023-08-28 15:13:021374瀏覽

Laravel 5中的仓储模式

儲存庫模式是由 Eric Evans 在他的領域驅動設計書中首次引入的。 事實上,儲存庫是應用程式存取網域層的入口點。

簡單來說,儲存庫允許您的所有程式碼使用對象,而無需知道對像是如何持久化的。儲存庫包含持久性的所有知識,包括從表到物件的映射。這提供了持久層的更面向物件的視圖,並使映射程式碼更加封裝。

讓你的儲存庫在 Laravel 中運作(作為一個真正的儲存庫——Eric Evans 領域驅動設計書)的唯一方法是將預設的 ORM 從活動記錄更改為資料映射器。最好的替代品是教義。

學說 ORM

Doctrine 是一種 ORM(物件關聯映射),它實現了資料映射器模式,並允許您將應用程式的業務規則與資料庫的持久層完全分開。 Doctrine 使用 DQL,而不是 SQL。 DQL 為您帶來物件查詢語言,這表示您將使用物件術語進行查詢,而不是傳統的關係查詢術語。

它允許您以物件導向的方式編寫資料庫查詢,並在您需要以使用預設儲存庫方法無法實現的方式查詢資料庫時提供協助。在我看來,DQL 是與資料庫保持聯繫的最強大方式。

教條與雄辯

Doctrine 實體只是一個普通的 PHP 簡單類,不會增加任何 ORM 繼承的開銷。 Doctrine 使用相同的繼承來管理多個查詢請求,而無需存取資料庫,這表示整個請求都存在實體物件。

Doctrine 的另一個不錯的功能是,無需遷移檔案來建立資料庫模式,而是自動建立資料庫來反映實體註解中的元資料。另一方面,Eloquent 不太複雜且非常易於使用。

這兩者之間的完整比較需要一篇單獨的文章。正如您所看到的,Doctrine 物件更輕、更抽象。然而,Doctrine 只適合特定的項目,因此它有時可能會為您帶來開銷。我相信這取決於程式設計師為應用程式選擇最好的 ORM。

部落格應用程式

現在是時候使用 Laravel 建立一個部落格應用程式了。首先,我們需要建立教義。有一個橋樑可以與 Laravel 5 的現有配置進行匹配。要在 Laravel 專案中安裝 Doctrine 2,我們執行以下命令:

composer require laravel-doctrine/orm

像往常一樣,該套件應該添加到app/config.php ,作為服務提供者:

LaravelDoctrine\ORM\DoctrineServiceProvider::class,

也應該要配置別名:

'EntityManager' => LaravelDoctrine\ORM\Facades\EntityManager::class

最後,我們發布套件配置:

php artisan vendor:publish --tag="config"

現在我們已經完成了。

實體是應用程式 App\Entities\Post.php 的重要組成部分:


namespace App\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity
 * @ORM\Table(name="posts")
 * @ORM\HasLifecycleCallbacks()
 */
class Post
{
    /**
     * @var integer $id
     * @ORM\Column(name="id", type="integer", unique=true, nullable=false)
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     *
     */
    private $id;

    /**
     * @ORM\Column(type="string")
     */
    private $title;

    /**
     * @ORM\Column(type="text")
     */
    private $body;

    public function __construct($input)
    {
        $this->setTitle($input['title']);
        $this->setBody($input['body']);
    }

    public function setId($id)
    {
        return $this->id=$id;
    }

    public function getId()
    {
        return $this->id;
    }

    public function getTitle()
    {
        return $this->title;
    }

    public function setTitle($title)
    {
        $this->title = $title;
    }

    public function getBody()
    {
        return $this->body;
    }

    public function setBody($body)
    {
        $this->body = $body;
    }
}

現在是時候創建儲存庫了,這在前面已經描述過了。 App/Repositories/PostRepo.php :

#
namespace App\Repository;

use App\Entity\Post;
use Doctrine\ORM\EntityManager;
class PostRepo
{

    /**
     * @var string
     */
    private $class = 'App\Entity\Post';
    /**
     * @var EntityManager
     */
    private $em;


    public function __construct(EntityManager $em)
    {
        $this->em = $em;
    }


    public function create(Post $post)
    {
        $this->em->persist($post);
        $this->em->flush();
    }

    public function update(Post $post, $data)
    {
        $post->setTitle($data['title']);
        $post->setBody($data['body']);
        $this->em->persist($post);
        $this->em->flush();
    }

    public function PostOfId($id)
    {
        return $this->em->getRepository($this->class)->findOneBy([
            'id' => $id
        ]);
    }

    public function delete(Post $post)
    {
        $this->em->remove($post);
        $this->em->flush();
    }

    /**
     * create Post
     * @return Post
     */
    private function perpareData($data)
    {
        return new Post($data);
    }
}

控制器:App/Http/Controllers/PostController.php :

#
namespace App\Http\Controllers;
use App\Repository\PostRepo as repo;
use App\Validation\PostValidator;


class PostController extends Controller
{
    private $repo;

    public function __construct(repo $repo)
    {
        $this->repo = $repo;
    }

    public function edit($id=NULL)
    {
        return View('admin.edit')->with(['data' => $this->repo->postOfId($id)]);
    }

    public function editPost()
    {
        $all = Input::all();
        $validate = PostValidator::validate($all);
        if (!$validate->passes()) {
            return redirect()->back()->withInput()->withErrors($validate);
        }
        $Id = $this->repo->postOfId($all['id']);
        if (!is_null($Id)) {
            $this->repo->update($Id, $all);
            Session::flash('msg', 'edit success');
        } else {
            $this->repo->create($this->repo->perpare_data($all));
            Session::flash('msg', 'add success');
        }
        return redirect()->back();
    }

    public function retrieve()
    {
        return View('admin.index')->with(['Data' => $this->repo->retrieve()]);
    }

    public function delete()
    {
        $id = Input::get('id');
        $data = $this->repo->postOfId($id);
        if (!is_null($data)) {
            $this->repo->delete($data);
            Session::flash('msg', 'operation Success');
            return redirect()->back();
        } else {
            return redirect()->back()->withErrors('operationFails');
        }
    }
}

如您所見,我使用 Flash 助理來管理訊息(您可以使用 Laravel 的)。關於驗證器,我應該補充一點,您可以建立自己的驗證器(就像我一樣)或使用 Laravel 預設值,這取決於您的偏好。

查看文件與平常相同。在此範例檢視中,檔案看起來像 resources/views/admin/edit.blade.php :


  
        
          @if (Session::has('flash_notification.message'))
            
                ×
                {!! Session::get('flash_notification.message') !!}
            
            @endif
            
          
                @if($errors->has())
                    
                        @foreach ($errors->all() as $error)
                            
                                {!! $error !!}
                            
                        @endforeach

                    
                @endif
                
                
                    
                        
                            {!! 'title' !!}

                        
                         
                    
                    
                        
                            {!! 'Body' !!}
 {!!  is_object($ListData)?$ListData->getTitle():'' !!} 

                        
                         
                    
                

                
                    
                    
                        
                             {!! 'save' !!}
                        
                    
                
                
            
        

以上是Laravel 5中的倉儲模式的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn