关于laravel 框架实现路由自动注入解决方法
有些系统需要自定义用户路由,而且这些路由保存在DB数据库表里。如图
有人问怎么实现自动注入呢?我个人看了些API文档。来个简单粗爆的方法:
1.创建SelfRouteServiceProvider.php(名称自已命名,自己喜欢就好);
2.在app.php 添加 App\Providers\SelfRouteServiceProvider::class,
代码如下:
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use Cache;
class SelfRouteServiceProvider extends ServiceProvider
{
public function boot()
{
$routes = Cache::remember('routes', webconfig('SYSCACHETIME') , function() {
return \App\Models\Routes\Routes::get();
});
foreach($routes as $router) {
app()->make('router')->get($router->path, $router->controller)->name($router->routename);
}
}
3.以上基本功能实现了。
4.为了实现整个流程能跑通。在创建HomeController控制器,代码如下:
namespace App\Http\Controllers\Home;
use Illuminate\View\View;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Cache;
class HomeController extends Controller
{
public function index(Request $request)
{
return view(‘post’);
}
public function forward(Request $request)
{
//这里是控制器方法:如 ArticleController 下的show 方法
$fuction = "show";
$Controller = "ArticleController";
return app('App\\Http\\Controllers\\Home\\'.$Controller)->$fuction($request);
}
}
5.大功造成。这只是例子,实际应用中,自己封装好基类的路由转发。
本作品采用《CC 协议》,转载必须注明作者和本文链接
推荐文章: