gpt4 book ai didi

php - 如何将路由转发到 Laravel?

转载 作者:可可西里 更新时间:2023-11-01 00:09:18 27 4
gpt4 key购买 nike

我们有一个具有自定义 ACL 和路由设置的旧网站。我们正在慢慢将代码库迁移到 Laravel。

为了从旧站点访问页面,当前所有内容都通过名为 Modules.php 的文件运行,modname 指定应打开哪个页面。例如:/Modules.php?modname=hello/world 显示世界页面。

我如何伪造 laravel 的路由?我想从 Modules.php 启动 Laravel 并使用 modname 作为路由。

所以我应该能够做这样的事情:Route::get('/hello/world', 'MyController@hello');

现在我只是简单地覆盖了 $_SERVER,但这样做的问题是获取基本 URL 之类的问题。

如果将来有人想这样做,我们就是这样做的:

$request = Request::createFromGlobals();
$request->server->set('REQUEST_URI', $_REQUEST['modname']);
$app->run($request);

在 laravel 5 中,你可以通过传递 $request 输入内核来做同样的事情(使用 public/index.php 作为引用)

关于如何判断一个路由是不是laravel路由,我做了这个功能。您可能可以通过使 json 文件成为二叉树来优化它,但我没有注意到性能问题,所以我没有费心。

<?php

/**
* Checks if Laravel should handle the request.
*
* @param $route string The route used internally by Laravel. Ex: sss/events
* @return boolean Whether Laravel creates the response for this route
*/
function IsLaravelRoute($route)
{
// The json file is made by running `php artisan routes:dump` in Laravel
// We compile the routes for performance by defering booting Laravel
// only if we know for sure that it is needed
$routeFilePath = realpath(__DIR__.'/../laravel.json');

// If Laravel isn't installed on the site, it's obviously not a Laravel route
if ($routeFilePath === false) {
return false;
}

// An array of objects with details foreach Laravel route
$laravelRoutes = json_decode(file_get_contents($routeFilePath));

// Some info we'll need to verify the route adheres to a route pattern
$requestMethod = $_SERVER['REQUEST_METHOD'];
$route = trim($route, '/');
$segments = explode('/', $route);
$len = count($segments);

foreach($laravelRoutes as $laravelRoute) {
// Format the laravel route details in such a way we can compare
// it with the route being checked
$routeSegments = explode('/', $laravelRoute->uri);
$routeLen = count($routeSegments);
$optionalParamCount = preg_match_all('/(\{.*\?\})/', $laravelRoute->uri);

// These conditions must be true; otherwise, we skip this iteration.
$sameMethods = in_array($requestMethod, $laravelRoute->methods);
$sameSegmentCount = $len === $routeLen;

// See if optional params can meet us half way
$routeDiff = $routeLen - $len;

// Possibly a route, we'll verify that
// it is in fact one later if this is true
$potentialRoute = $optionalParamCount >= $routeDiff && $routeDiff >= 0;

$looksLegit = $sameMethods && ($sameSegmentCount || $potentialRoute);
if (!$looksLegit) {
continue; // Ain't nobody got time for that
}

// Basic requirements for elgibility is there -- now verify
for ($i = 0; $i < $len; $i++) {
// We can only validate concrete route segments;
// we have to give the benefit of the doubt to route parameters.
$validate = !preg_match('/\{.*\}/', $routeSegments[$i]);
if ($validate && $segments[$i] !== $routeSegments[$i]) {
// This route isn't valid, but let's check the next $laravelRoute
continue 2;
}
}

// This route is legit
return true;
}

// Looked through all the routes, but looks like it isn't a Laravel page :(
return false;
}

当然,我们想使用命名路由,这样 Laravel 会生成新路由,但为了做到这一点,我们扩展了 UrlGenerator。请原谅全局变量。

<?php namespace Focus\Core\Route;

/**
* When the time comes just remove this class
* and use the default Laravel UrlGenerator class
*/
class UrlGenerator extends \Illuminate\Routing\UrlGenerator
{
/**
* We build the URL that is needed. This will pass everything through
* Modules.php
*
* @param \Illuminate\Routing\Route $route
* @param array $parameters
* @param bool $absolute
* @return string
*/
protected function toRoute($route, array $parameters, $absolute)
{
global $FocusURL;

$modname = $this->replaceRouteParameters($route->uri(), $parameters);

if (sizeof($parameters) > 0) {
// Append query string onto existing
$queryString = $this->getRouteQueryString($parameters);
$queryString = '&'.substr($queryString, 1);
} else {
$queryString = '';
}

$url = '/Modules.php?modname='.$modname.$queryString;

return $absolute ? rtrim($FocusURL, '/').$url : ltrim($url, '/');
}

/**
* Generate a URL to an application asset.
*
* @param string $path
* @param bool $secure
* @return string
*/
public function asset($path, $secure = null)
{
global $FocusURL;

if ($this->isValidUrl($path)) return $path;

// Shortcut to access a package's assets
if (strpos($path, '@') === 0) {
$path = 'packages/focus/'.substr($path, 1);
}

$path = ltrim($path, '/');
$filePath = base_path().'/public/'.$path;

// Prevent loading old version of assets due to caching
if (file_exists($filePath)) {
$path .= '?'.filemtime($filePath);
}

return rtrim($FocusURL, '/').'/laravel/public/'.$path;
}
}

至于 laravel.json 文件是如何到达那里供 IsLaravel 函数检查的,我们制作了这个 artisan 命令,我们用 gulp 观察它的变化

<?php namespace Focus\Core\Command;

use Illuminate\Console\Command;
use Illuminate\Routing\Route;
use Illuminate\Routing\Router;
use Illuminate\Support\Facades\File;

use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputArgument;

class RouteDumper extends Command {

/**
* The console command name.
*
* @var string
*/
protected $name = 'routes:dump';

/**
* The console command description.
*
* @var string
*/
protected $description = 'Creates a file that can be included in old focus to find laravel routes without starting the entire framework each request.';

protected $router;
protected $routes;

/**
* Create a new command instance.
*
* @return void
*/
public function __construct(Router $router)
{
parent::__construct();
$this->router = $router;
$this->routes = $router->getRoutes();
}

/**
* Execute the console command.
*
* @return mixed
*/
public function fire()
{
$json = array();
foreach ($this->routes as $route) {
$json[] = array(
'methods' => $route->methods(),
'uri' => $route->uri()
);
}

$path = base_path().'/../laravel.json';
$fileContents = json_encode($json);
File::put($path, $fileContents);

//$this->call("generate:laroute");

$this->info('All routes have been dumped!');
}

/**
* Get the console command arguments.
*
* @return array
*/
protected function getArguments()
{
return array();
}

/**
* Get the console command options.
*
* @return array
*/
protected function getOptions()
{
return array();
}

}

最佳答案

你可以使用 Request::create 方法创建一个请求,就像这样

// Get the url
$modname = "hello/world";

$request = Request::create($modname, 'GET', array());
return Route::dispatch($request);

关于php - 如何将路由转发到 Laravel?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20748080/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com