【发布时间】:2017-12-26 01:35:36
【问题描述】:
当我没有找到自动路由的最佳解决方案时,我编写了代码。
任何建议将不胜感激。
在您的 routes.php 文件中,在文件末尾写下这一行
Route::match(["get","post"], '/{controller}/{method?}/{parameter?}', "Routes@index");
现在在 App\HTTP\Controllers 中创建一个新类
Routes.php(您可以更改名称)
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
class Routes extends Controller
{
public function index($controller,$method="",$parmeter=""){
$controller = ucfirst($controller);
if(empty($method)){
// e.g: example.com/users
// will hit App\Http\Controllers\Users\Users.php Class Index method
return \App::call("App\Http\Controllers\\$controller\\$controller@index");
}
// e.g: example.com/users/list
// will hit App\Http\Controllers\Users\Users.php Class List method
// If user.php has List method then $parameters will pass
$app = \App("App\Http\Controllers\\$controller\\$controller");
if(method_exists($app, $method)){
return $app->$method($parmeter);
}
// If you have a folder User and have multiple class in users folder, and want to access other class
// e.g: example.com/users/groups
// will hit App\Http\Controllers\Users\Groups.php Class Index method
$method = ucfirst($method); //Now method will be use as Class name
$app = \App("App\Http\Controllers\\$controller\\$method");
return $app->index();
}
}
完成
现在在控制器文件夹中创建你的类,它会自动路由...
你的文件结构例如:
App
HTTP
Controllers
Users
Users.php
Groups.php
Etc.php
Post
Post.php
Banners
Banners.php
Folder
File.php
现在你有了想法,你可以根据你的风格改变逻辑,或者你可以使用它。
我使用的是 Laravel 5.2
【问题讨论】:
-
问题是?
-
没问题,我提供自动路线的解决方案,但任何建议都将不胜感激。
-
当您发布此内容时,您必须按下标有“”的按钮这一事实是否表明您应该只使用该按钮来提问?虽然我很欣赏这是共享代码,但这不是这样做的合适地方,StackExchange 有像 CodeReview 这样的地方,这些地方可以接受这类帖子。
标签: php laravel codeigniter routes