Created
June 7, 2020 09:50
-
-
Save kennedy-osaze/9ec02e2ef5c7c758fbdd177333ef943b to your computer and use it in GitHub Desktop.
Simple Repository in Laravel
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App; | |
use Illuminate\Database\Eloquent\Model; | |
class Product extends Model | |
{ | |
// | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Http\Controllers; | |
use App\Http\Controllers\Controller; | |
use App\Repository\ProductRepository; | |
class ProductController extends Controller | |
{ | |
protected ProductRepository $products; | |
public function __construct(ProductRepository $products) | |
{ | |
$this->products = $products; | |
} | |
public function show(string $name) | |
{ | |
dd($this->products->where($name)->first(), $this->products->findByName($name)); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Repository; | |
use App\Product; | |
class ProductRepository extends Repository | |
{ | |
protected string $model = Product::class; | |
public function findByName(string $name): ?Product | |
{ | |
return $this->where($name)->first(); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Repository; | |
abstract class Repository | |
{ | |
protected string $model; | |
public function __call($name, $arguments) | |
{ | |
return app(static::$model)->{$name}(...$arguments); | |
} | |
public function __callStatic($name, $arguments) | |
{ | |
return app(static::class)->{$name}(...$arguments); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment