Simple repository pattern for laravel, with services!

Overview

Simple repository pattern for laravel, with services!

With easy repository, you can have the power of the repository pattern, without having to write too much code altogether. The package automatically binds the interfaces to the implementations, all you have to do is change in the configuration which implementation is being used at the moment!

Total Downloads PHP Version

Requirement

  • Laravel 8
  • PHP 7.4||8.*

Installation

You can install the package via composer:

composer require yaza/laravel-repository-service

Quick usage

This package overrides the default laravel php artisan make:model User command, and adds a few flags that can help you set up repository and service quickly.

// will genearate controller, factory, service, seeder, repository, resource and migration
php artisan make:model User --all

// use the service and repository flag to generate the class
php artisan make:model User --service --repository

// use the short form to generate model with service and repository
php artisan make:model User -sr -rt

You can also create only the repository, or service, or both:

php artisan make:repository User
// or
php artisan make:repository UserRepository

// or create together with a service
php artisan make:repository User --service
// or
php artisan make:repository UserRepository --service

// or create a service separately
php artisan make:service User
// or
php artisan make:service UserService

The php artisan make:repository User will generate two files. One for the interface, and one for the repository class. The interface is bound to it's counter part class automatically depending on the current implementation being used. If the implementation for an interface is not provided, you can provide one manually or otherwise, attempting to use the service will bring up an error.

Eloquent is the default implementation. Other implementations will be added in the future. This is because the package was mainly to simplify usage of the repository pattern in laravel. The classes created are:

// app/Repositories/Interfaces/UserRepository.php



namespace App\Repositories\Interfaces;

use LaravelEasyRepository\Repository;

class UserRepositoryInterface extends Repository{

    // Write something awesome :)
}

and,

// app/Repositories/Eloquent/UserRepository.php



namespace App\Repositories\Eloquent;

use LaravelEasyRepository\Repository;
use LaravelEasyRepository\Implementations\Eloquent;
use App\Repositories\Interfaces\UserRepositoryInterface;

class UserRepository extends Eloquent implements UserRepositoryInterface{

    /**
    * Model class to be used in this repository for the common methods inside Eloquent
    * Don't remove or change variable $model or $this->model
    * @property Model|mixed $model;
    */
    protected $model;

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

also if you included the services flag, or created one by running a command, the service file generated is:

// app/Services/UserService



namespace App\Services;

use {repositoryInterfaceNamespace}\{repositoryInterface};
class UserService {

     /**
    * The repository interface to use in this service.
    */
    protected $mainRepository;

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

    // Define your custom methods :)
}

In your controller you can use the service but only call interfaces auto bind to repository.



namespace App\Http\Controllers;

use App\Services\UserService;
use Illuminate\Http\Request;

class UserController extends Controller
{
    public function __construct(UserService $mainService)
    {
        $this->mainService = $mainService;
    }
    
    public function all () {
      return $this->mainService->all();
    }

}

The repository and service also comes in built with 5 common CRUD methods

interface Repository
{
    /**
     * Fin an item by id
     * @param int $id
     * @return Model|null
     */
    public function find(int $id);

    /**
     * Return all items
     * @return Collection|null
     */
    public function all();

    /**
     * Return query builder instance to perform more manouvers
     * @return Builder|null
     */
    public function query();

    /**
     * Create an item
     * @param array|mixed $data
     * @return Model|null
     */
    public function create($data);

    /**
     * Update a model
     * @param int|mixed $id
     * @param array|mixed $data
     * @return bool|mixed
     */
    public function update($id, array $data);

    /**
     * Delete a model
     * @param int|Model $id
     */
    public function delete($id);

    /**
     * multiple delete
     * @param array $id
     * @return mixed
     */
    public function destroy(array $id);

}

Addons for build rest api with Response, Result Service like

  • in service


namespace App\Services;

use LaravelEasyRepository\Traits\ResultService;
use {repositoryInterfaceNamespace}\{repositoryInterface};

class UserService {
 use ResultService;

     /**
    * The repository interface to use in this service.
    */
    protected $mainRepository;

    public function __construct({repositoryInterface} $mainRepository)
    {
        $this->mainRepository = $mainRepository;
    }
    
    public function all () {
        try {
            $result = $this->mainRepository->all();
            return $this->setStatus(true)
                        ->setResult($result)
                        ->setCode(200)
                        ->setMessage('your message');
        } catch (\Exception $e) {
            return $this->exceptionResponse($e);
        }            
    }    
}
  • in controller


namespace App\Http\Controllers;

use App\Services\UserService;
use Illuminate\Http\Request;
use LaravelEasyRepository\Traits\Response;

class UserController extends Controller
{
   use Response;
    public function __construct(UserService $mainService)
    {
        $this->mainService = $mainService;
    }
    
    public function all () {
      $result = $this->mainService->all();
      return $this->responseJson(
        $result->getStatus(),
        $result->getMessage(),
        $result->getResult(),
        $result->getCode()
      );
    }

}
  • output or response like
{
    "success": true,
    "code": 200,
    "message": 'Your message',
    "data": [
        {
            "id": 1,
            "name": "tes",
            "email": "[email protected]",
            "email_verified_at": null,
            "created_at": null,
            "updated_at": null
        }
    ]
}

You can publish the config file with:

php artisan vendor:publish --provider="LaravelEasyRepository\LaravelEasyRepositoryServiceProvider" --tag="easy-repository-config"

The configurations in the config file are standard, and can be extended with/depending on further requirements. No need to change any of the contents, unless you are very aware of what you are doing :) This is the contents of the published config file:

"app/Repositories", /** * Default repository namespace */ "repository_namespace" => "App\Repositories", /** * The directory for all the services */ "service_directory" => "app/Services", /** * Default service namespace */ "service_namespace" => "App\Services", /** * Default repository implementation */ "default_repository_implementation" => "Eloquent", /** * Current repository implementation */ "current_repository_implementation" => "Eloquent", ]; ">
return [
    /**
     * The directory for all the repositories
     */
    "repository_directory" => "app/Repositories",

    /**
     * Default repository namespace
     */
    "repository_namespace" => "App\Repositories",

    /**
     * The directory for all the services
     */
    "service_directory" => "app/Services",

    /**
     * Default service namespace
     */
    "service_namespace" => "App\Services",

    /**
     * Default repository implementation
     */
    "default_repository_implementation" => "Eloquent",

    /**
     * Current repository implementation
     */
    "current_repository_implementation" => "Eloquent",
];

Changelog

Please see CHANGELOG for more information on what has changed recently.

License

The MIT License (MIT). Please see License File for more information.

You might also like...
Laravel Cashier provides an expressive, fluent interface to Stripe's subscription billing services.

Introduction Laravel Cashier provides an expressive, fluent interface to Stripe's subscription billing services. It handles almost all of the boilerpl

Prepare your Laravel apps incredibly fast, with various commands, services, facades and boilerplates.

Grafite Builder Grafite has archived this project and no longer supports or develops the code. We recommend using only as a source of ideas for your o

Skosmos is a web-based tool providing services for accessing controlled vocabularies, which are used by indexers describing documents and searchers looking for suitable keywords.

Skosmos is a web-based tool providing services for accessing controlled vocabularies, which are used by indexers describing documents and searchers looking for suitable keywords.

A PHP library to convert text to speech using various services

speaker A PHP library to convert text to speech using various services

MajorDoMo is an open-source DIY smarthome automation platform aimed to be used in multi-protocol and multi-services environment.
MajorDoMo is an open-source DIY smarthome automation platform aimed to be used in multi-protocol and multi-services environment.

MajorDoMo (Major Domestic Module) is an open-source DIY smarthome automation platform aimed to be used in multi-protocol and multi-services environment. It is based on web-technologies stack and ready to be delivered to any modern device. It is very flexible in configuration with OOP paradigm used to set up automation rules and scripts. This platform can be installed on almost any personal computer running Windows or Linux OS.

Redmine API services
Redmine API services

DevMakerLab/My-Mine Want to track and analyze your Redmine tickets/projects, Installation Examples Installation ⚠️ Requires = PHP 7.4 ⚠️ composer req

A collection of samples that demonstrate how to call Google Cloud services from PHP.

PHP Docs Samples A collection of samples that demonstrate how to call Google Cloud services from PHP. See our other Google Cloud Platform github repos

A collection of samples that demonstrate how to call Google Cloud services from PHP.

PHP Docs Samples A collection of samples that demonstrate how to call Google Cloud services from PHP. See our other Google Cloud Platform github repos

A cross-language remote procedure call(RPC) framework for rapid development of high performance distributed services.

Motan Overview Motan is a cross-language remote procedure call(RPC) framework for rapid development of high performance distributed services. Related

Comments
  • cant install package

    cant install package

    Problem 1 - Root composer.json requires yaza/laravel-repository-service ^1.5 -> satisfiable by yaza/laravel-repository-service[V1.5.15]. - yaza/laravel-repository-service V1.5.15 requires illuminate/contracts ^8.37 -> found illuminate/contracts[v8.37.0, ..., 8.x-dev] but these were not loaded, likely because it conflicts with another require.

    i’m using laravel 9, and cannot install illuminate/contracts at the same time Only one of these can be installed: laravel/framework[v8.0.0, ..., 8.x-dev], illuminate/contracts[v9.0.0]. laravel/framework replaces illuminate/contracts and thus cannot coexist with it.

    opened by fasaya 3
  • Error when add service

    Error when add service

    file_put_contents(/media/bagong/New Volume/laravel/ServicePatternPackage/app/Services/User/UserService.php): Failed to open stream: No such file or directory

    at vendor/laravel/framework/src/Illuminate/Filesystem/Filesystem.php:190 186▕ * @return int|bool 187▕ / 188▕ public function put($path, $contents, $lock = false) 189▕ { ➜ 190▕ return file_put_contents($path, $contents, $lock ? LOCK_EX : 0); 191▕ } 192▕ 193▕ /* 194▕ * Write the contents of a file, replacing it atomically if it already exists.

    opened by zikrisuanda11 0
  • Error create service

    Error create service

    error if run : sail artisan make:repository UserRepository --service or want to generate service file_put_contents(/var/www/html/app/Services/User/UserService.php): Failed to open stream: No such file or directory @yaza-putu

    opened by jrpikong 0
  • Argument --service error on linux

    Argument --service error on linux

    Halo mas, ini saya dulu pake windows tapi udh migrasi ke linux, ketika make command --service saya menemukan package ini membuat folder App baru didalam directory laravel.

    Untuk di linux saya harus membuat folder berdasarkan nama model agar bisa menggunakan argument --service.

    opened by ariexx 1
Releases(V3.2.7)
Owner
Yaz3
What's ngetorz?
Yaz3
Some Joomla! 4.x Web Services Api Examples and Experiments to raise the level of awareness of the huge potiental of Joomla! 4.x Web Services.

j4x-api-examples WHY? If you are a Joomla! developer or want to become a Joomla! developer there is a new resource for you The Official New Joomla! Ma

Mr Alexandre ELISÉ 11 Nov 29, 2022
this starter kite inspired by laravel & Geo and mvc pattern. it's wrap for Wordpress built in classes.

WordpressStarterKite Introduction Built With Prerequisite Directory Structure Guidelines Getting Started Authors Introduction this starter kite inspir

Omar Hossam Eldin Kandil 7 Aug 24, 2022
PHP implementation of circuit breaker pattern.

What is php-circuit-breaker A component helping you gracefully handle outages and timeouts of external services (usually remote, 3rd party services).

ArturEjsmont 169 Jul 28, 2022
PHP regexp pattern matching Unicode emojis

Emoji pattern This package provides regexp patterns to match Unicode emojis. All forms of emojis are matched, including: Single-character emoji ( ?? )

Incenteev 7 Nov 5, 2022
Design Pattern Examples in PHP

Design Patterns in PHP This repository is part of the Refactoring.Guru project. It contains PHP examples for all classic GoF design patterns. Each pat

Refactoring.Guru 909 Dec 22, 2022
Implementação do Composite Pattern Utilizando PHP

Composite Pattern - PHP Implementação do Composite Pattern Utilizando PHP Descrição O Composite Pattern é um padrão de projeto estrutural que permite

Anglesson Araújo 1 Jan 2, 2022
Pattern Lab Standard Edition for Twig

Pattern Lab Standard Edition for Twig The Standard Edition for Twig gives developers and designers a clean and stable base from which to develop a Twi

Pattern Lab 102 Oct 24, 2022
Glob-like file and pattern matching utility.

Glob-like file and pattern matching utility.

Chris Kankiewicz 94 Dec 14, 2022
This is a Native PHP MVC. If you will build your own PHP project in MVC with router, you can clone this ready to use MVC pattern repo.

Welcome to PHP-Native-MVC-Pattern ?? If you will build your own PHP project in MVC with router, you can clone this ready to use MVC pattern repo. Work

null 2 Jun 6, 2022
YL MVC Structure (PHP MVC) is a pattern made in PHP used to implement user interfaces, data, and controlling logic.

YL MVC Structure (PHP MVC) is a pattern made in PHP used to implement user interfaces, data, and controlling logic. It is built based on the combination of ideas from the Yii framework and Laravel framework (yl).

Tan Nguyen 3 Jan 3, 2023