Skip to content

Instantly share code, notes, and snippets.

@hiyali
Last active January 1, 2021 02:50
Show Gist options
  • Save hiyali/289e5c90be84afeb48c59dcc647301f0 to your computer and use it in GitHub Desktop.
Save hiyali/289e5c90be84afeb48c59dcc647301f0 to your computer and use it in GitHub Desktop.
lumen-route-resource

Files

Route

./routes/Resource.php # get model resource
./routes/web.php # include and define resource

Controller

./app/Http/Controllers/RestfulControllerTrait.php # restful trait
./app/Http/Controllers/Controller.php # use restful trait
./app/Http/Controllers/UserController.php # extends from below controller
<?php
namespace App\Http\Controllers;
use Laravel\Lumen\Routing\Controller as BaseController;
class Controller extends BaseController
{
/*
* For use restful trait.
*/
use RestfulControllerTrait;
}
<?php
if (function_exists('Resource')) {
throw new Error('Resource Already Exist!');
} else {
/**
* Create a rest Resource route
*
* @param $path
* @param $controller
* @param $name
* @param array $exclude
*/
function Resource ($path, $controller, $name = null, $exclude = [])
{
global $app;
if (!isset($name)) {
$name = $path;
}
/**
* get method items
*/
function g($method, $name, $pathExt = '')
{
return ['method' => $method, 'name' => $name, 'pathExt' => $pathExt];
}
/**
* Restful items.
*/
$restfulMethods = [
g('get', 'all', '/all'), // You can remove this line.
g('get', 'index'),
g('get', 'show', '/{id:\d+}'),
g('post', 'store'),
g('put', 'update', '/{id}'),
g('delete', 'destroy', '/{id}'),
];
foreach ($restfulMethods as $restItem) {
if (in_array($restItem['name'], $exclude)) {
continue;
}
$app->{$restItem['method']}($path . $restItem['pathExt'], [
'as' => $name .'.'. $restItem['name'],
'uses' => $controller .'@'. $restItem['name'],
]);
}
}
}
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
trait RestfulControllerTrait
{
/*
* For save restful api index method paginate default page size.
*/
private $perPage = 10; [60/677]
/*
* Get target controller's:
* 1. model Eloquent.
* 2. model rules.
*/
public function __construct(Request $request)
{
if (!isset($this->model)) {
throw new Error("ModelNotSet");
}
if (!isset($this->rules)) {
throw new \Exception("RulesNotSet");
}
}
/*
* Get resource list (paginate).
*/
public function index(Request $request)
{
$perPage = $request['per_page'] ?: $this->perPage;
$result = $this->model::paginate($perPage);
return response()->json($result, 200);
}
/*
* Get resource list (all).
* You can remove this function named all.
*/
public function all(Request $request) [29/677]
{
$result = $this->model::all();
return response()->json(['data' => $result], 200);
}
/*
* Get resource item with id.
*/
public function show(Request $request, $id)
{
$item = $this->model::findOrFail($id);
return response()->json(['data' => $item], 200);
}
/**
* For validate request.
*/
public function validateRequest(Request $request)
{
$this->validate($request, $this->rules);
}
/*
* Create new resource item.
*/
public function store(Request $request)
{
$this->validateRequest($request);
$item = $this->model;
$this->setItem($request, $item);
$item->save(); // $this->model::create($item);
return response()->json([], 200);
}
/*
* Update item that belongs to passed id.
*/
public function update(Request $request, $id)
{
$this->validateRequest($request);
$item = $this->model::findOrFail($id);
$this->setItem($request, $item);
$item->save();
return response()->json([], 200);
}
/*
* Delete item that belongs to passed id.
*/
public function destroy(Request $request, $id)
{
$item = $this->model::findOrFail($id);
$item->delete();
return response()->json([], 200);
}
}
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\User;
class UserController extends Controller
{
/*
* For private model Eloquent.
*/
protected $model;
/**
* For validate request.
*/
protected $rules = [
'name' => 'required',
'email' => 'required|email|unique:users'
];
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct(Request $request)
{
$this->model = new User;
parent::__construct($request);
}
public function setItem(&$req, &$item){
$item->title = $req->get('title');
$item->parent_id = intval($req->get('parent_id'));
$item->isShow = $req->get('isShow') == false ? false : true;
}
}
<?php
/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It is a breeze. Simply tell Lumen the URIs it should respond to
| and give it the Closure to call when that URI is requested.
|
*/
require_once __DIR__ . '/Resource.php';
$app->group([], function () use ($app)
{
Resource('user', 'UserController');
});
@hiyali
Copy link
Author

hiyali commented Aug 30, 2017

@shusharin Yes, it is.
The goal of setItem function is that you can do something before create/update the record, can you write an example for this? Thank you.

@hiyali
Copy link
Author

hiyali commented Aug 30, 2017

@shusharin I am updated that, but not test it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment