GithubHelp home page GithubHelp logo

jsdecena / baserepo Goto Github PK

View Code? Open in Web Editor NEW
75.0 6.0 42.0 62 KB

Base repository

License: MIT License

PHP 99.70% Makefile 0.30%
laravel laravel-5-package lumen repository-pattern repository lumen-package test-driven-development tdd php7 php

baserepo's Introduction

Base Repository Package

master Latest Stable Version Total Downloads License FOSSA Status

Buy me a coffeee so I can continue development of this package

How to install

  • Run in your terminal composer require jsdecena/baserepo

  • In your repository class, extend it so you can use the methods readily available.

namespace App\Repositories;

use App\User;
use Illuminate\Http\Request;
use Illuminate\Database\QueryException;
use Jsdecena\Baserepo\BaseRepository;

class UserRepository extends BaseRepository {
    
    public function __construct(User $user) 
    {
        parent::__construct($user);
    }
    
    public function createUser(array $data) : User
    {
        try {
            return $this->create($data);
        } catch (QueryException $e) {
            throw new \Exception($e);
        }
    }
}
  • Then, use it in your controller.
use App\Http\Controllers\Controller;
use App\Repositories\UserRepository;
use App\User;

class MyController extends Controller {
    
    private $userRepository;
    
    /**
    *
    * Inject your repository or the interface here
    */
    public function __construct(UserRepository $userRepository) 
    {
        $this->userRepository = $userRepository;
    }

    public function index() 
    {
        $user = $this->userRepository->all();

        return response()->json($user);    
    }
    
    public function store(Request $request)
    {
        // do data validation
    
        try {
            
            $user = $this->userRepository->createUser($request->all());
    
            return response()->json($user, 201);
        
        } catch (Illuminate\Database\QueryException $e) {
            
            return response()->json([
                'error' => 'user_cannot_create',
                'message' => $e->getMessage()
            ]);        
        }
    }

    public function show($id)
    {
        // do data validation
        
        try {
            
            $user = $this->userRepository->findOneOrFail($id);
    
            return response()->json($user);
            
        } catch (Illuminate\Database\Eloquent\ModelNotFoundException $e) {
            
            return response()->json([
                'error' => 'user_no_found',
                'message' => $e->getMessage()
            ]);
        }
    }
    
    public function update(Request $request, $id)
    {
        // do data validation
        
        try {
            
            $user = $this->userRepository->findOneOrFail($id);
           
            // You can also do this now, so you would not have to instantiate again the repository
            $this->userRepository->update($request->all(), $user);
    
            return response()->json($user);
            
        } catch (Illuminate\Database\Eloquent\ModelNotFoundException $e) {
            
            return response()->json([
                'error' => 'user_no_found',
                'message' => $e->getMessage()
            ]);            
            
        } catch (Illuminate\Database\QueryException $e) {
            
            return response()->json([
                'error' => 'user_cannot_update',
                'message' => $e->getMessage()
            ]);
        }
    }
    
    public function destroy($id)
    {
        // do data validation
        
        try {
            
            $user = $this->userRepository->findOneOrFail($id);
            
            // Create an instance of the repository again 
            // but now pass the user object. 
            // You can DI the repo to the controller if you do not want this.
            $userRepo = new UserRepository($user);
            $userRepo->delete()
    
            return response()->json(['data' => 'User deleted.']);
            
        } catch (Illuminate\Database\Eloquent\ModelNotFoundException $e) {
            
            return response()->json([
                'error' => 'user_no_found',
                'message' => $e->getMessage()
            ]);            
            
        } catch (Illuminate\Database\QueryException $e) {
            
            return response()->json([
                'error' => 'user_cannot_delete',
                'message' => $e->getMessage()
            ]);
        }
    }    
    
}

Testing

  • Run make test

Author

Jeff Simons Decena

License

FOSSA Status

baserepo's People

Contributors

edwinwongnetccentric avatar faks avatar fossabot avatar jsdecena avatar kcpal-qode avatar michaelmano avatar mikedodd avatar naufalhsyahputra avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

baserepo's Issues

Eloquent relations

Is there anyway to use Eloquent relations with this project?

I've checked your code in Laracom project and I found this:

$order = $this->orderRepo->findOrderById($orderId);
$order->courier = $this->courierRepo->findCourierById($order->courier_id);
$order->address = $this->addressRepo->findAddressById($order->address_id);

https://github.com/Laracommerce/laracom/blob/6e5e147db363722be2e277f339e39cf5324a9101/app/Http/Controllers/Admin/Orders/OrderController.php#L120

Would you please tell me what's the point of not using Eloquent relations in the Repository design pattern?

BR

Why not using dependency injection in controllers ?

As as title says, thats my question basically. It would be a nicer way to inject repos inside controller and execute repository methods rather than initialize repositories inside controllers action. Any reason for doing this way?

Wrong Instance Type

I keep getting this error when trying to install the package via composer.

In BaseRepository.php line 43:

Argument 1 passed to Jsdecena\Baserepo\BaseRepository::__construct() must b
e an instance of Illuminate\Database\Eloquent\ModelModel, instance of Illum
inate\Foundation\Application given, called in /Applications/MAMP/htdocs/dai
lyeatz/vendor/laravel/framework/src/Illuminate/Foundation/ProviderRepositor
y.php on line 208

Unresolvable dependency resolving

I have installed and added configurations in app\providers;
but I get an error

controller:

     private $ userRepo;

     public __construct function (UserInterface $ userRepository)
     {
         $ this-> userRepo = $userRepository;
     }

     public function index () {
         $ results = $ this->userRepo->listUsers ();
         print $ results;
    }

interface:

UserInterface interface extends BaseRepositoryInterface {
    
    public function listUsers ($ columns = array ('*'), string $ orderBy = 'id', string $ sortBy = 'asc'): 
   Collection;
    
}

baseRepo:

 public function __construct (User $ user)
     {
         $ this-> model = $user;
        
     }
 
public function listUsers ($columns = array ('*'), string $orderBy = 'id', string $sortBy = 'asc'): Collection
     {
         return $ this->all ($columns, $orderBy, $sortBy);
     }

Error display when installing the package

The package successfully installed but there was an error display in the command line.
I'm using fresh Laravel 6.0

In BaseRepository.php line 43:

  Argument 1 passed to Jsdecena\Baserepo\BaseRepository::__construct() must b
  e an instance of Illuminate\Database\Eloquent\Model, instance of Illuminate
  \Foundation\Application given, called in /home/kenneth/Sites/test1/vendor/l
  aravel/framework/src/Illuminate/Foundation/ProviderRepository.php on line 2
  08


Script @php artisan package:discover --ansi handling the post-autoload-dump event returned with error code 1

Paginate array data return key value

the paginateArrayResults() return the data with key because of array_slice(). kindly wrap around array_values(). end result like this...

array_values(array_slice($data, $offset, $perPage, true))

I cant make a pull request (permission deneid).

Wrong Instance Type After Composer Update

In the previous version I was not facing any issue, when I tried running the command 'composer update' I am getting this issue.

I have also tried your solution but nothing worked, can you please suggest us with few more solutions?

Argument 1 passed to Jsdecena\Baserepo\BaseRepository::__construct() must be an instance of Illuminate\Database\Eloquent\Model, instance of Illuminate\Foundation\Application given, called in /var/www/html/carbanio/vendor/laravel/framework/src/Illuminate/Foundation/ProviderRepository.php on line 208

Issue with base repository

Hi everyone, I am getting this error after I updated the composer. can you please let me know what the issue is

In BaseRepository.php line 43:

Argument 1 passed to Jsdecena\Baserepo\BaseRepository::__construct() must b
e an instance of Illuminate\Database\Eloquent\Model, instance of Illuminate
\Foundation\Application given, called in /vendor/laravel/framework/src/Illuminate/Foundation/Provid
erRepository.php on line 208

Hope to get solution

Pagination with getData method doesn't parse the include transformer

Hi Jeff, im trying to use this package for my project, but problem comes when i need pagination feature for each of my API. when i trying to find on documentation. it doesn't exist. but when i look into the code, i found some method that can generated the pagination and meta cursor automatically. the method i use for it are getData()
i parse my query builder and transformer on that method. it works as well, but when i parse include param url on my api. it doesn't parse the include data. i figuring out what happened, and i know that in getData() method there is no code which execute the parseIncludes() method. so i add some line of code to fix this.
if (isset($_GET['include'])) { $manager->parseIncludes($_GET['include']); }

i know it's not good to change the code inside vendor folder because it will be removed if someone join in my project. so is there any proper way to doing pagination also parsing the include data in my transformer? with my pleasure i will make a PR and adding pagination documentation if not yet implemented on this package.
thanks for make this package

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.