PHP7的路由库
我需要为php使用路由插件,我决定使用nikic/FastRoute[。但是,由于我对php的知识有限,我仍然无法成功地使用它 这是我的密码PHP7的路由库,php,routing,autoload,php-7,Php,Routing,Autoload,Php 7,我需要为php使用路由插件,我决定使用nikic/FastRoute[。但是,由于我对php的知识有限,我仍然无法成功地使用它 这是我的密码 require_once 'FastRoute/src/functions.php'; # create a stack of actions $dispatcher = FastRoute\simpleDispatcher(function(FastRoute\RouteCollector $r) { $r->addRoute('GET'
require_once 'FastRoute/src/functions.php';
# create a stack of actions
$dispatcher = FastRoute\simpleDispatcher(function(FastRoute\RouteCollector $r) {
$r->addRoute('GET', '/', 'get_all_users_handler');
// {id} must be a number (\d+)
$r->addRoute('GET', '/contract-management', 'get_user_handler');
// The /{title} suffix is optional
$r->addRoute('GET', '/articles/{id:\d+}[/{title}]', 'get_article_handler');
});
// Fetch method and URI from somewhere
$httpMethod = $_SERVER['REQUEST_METHOD'];
$uri = $_SERVER['REQUEST_URI'];
// Strip query string (?foo=bar) and decode URI
if (false !== $pos = strpos($uri, '?')) {
$uri = substr($uri, 0, $pos);
}
$uri = rawurldecode($uri);
$routeInfo = $dispatcher->dispatch($httpMethod, $uri);
switch ($routeInfo[0]) {
case FastRoute\Dispatcher::NOT_FOUND:
// ... 404 Not Found
break;
case FastRoute\Dispatcher::METHOD_NOT_ALLOWED:
$allowedMethods = $routeInfo[1];
// ... 405 Method Not Allowed
break;
case FastRoute\Dispatcher::FOUND:
$handler = $routeInfo[1];
$vars = $routeInfo[2];
// ... call $handler with $vars
break;
}
function get_user_handler(){
print_r("here");
}
function get_article_handler(){
print_r("article handler");
}
我刚刚将示例代码中的require'/path/to/vendor/autoload.php';改为require_once'FastRoute/src/functions.php'。但下面显示了错误
致命错误:未捕获错误:在C:\wamp\www\testproj\includes\FastRoute\src\functions中找不到类“FastRoute\RouteCollector”。php:21堆栈跟踪:#0 C:\wamp\www\testproj\includes\routing.php(13):FastRoute\simpleDispatcher(对象(闭包))#1 C:\wamp\www\testproj\index.php(9):require##once('C:\wamp\www\testp…'))#2{main}在第21行的C:\wamp\www\testproj\includes\FastRoute\src\functions.php中抛出
我想我的设置有问题。但我仍然找不到更好的初学者示例。因此,请告诉我我哪里做错了。提前谢谢。请阅读
您的问题在于删除该行
require '/path/to/vendor/autoload.php';
这个PHP脚本安装一个自动加载程序,当某些需要的PHP类未知时,自动加载必要的PHP脚本文件
如果出于某种原因您不需要这个自动加载器,那么您必须通过其他方式加载所需的类
因此,大多数情况下,您确实需要这个自动加载器,因为它使生活更加轻松,代码也更短。您已经提到了您的错误:“我刚刚将示例代码中的require'/path/to/vendor/autoload.php';改为require_once'FastRoute/src/functions.php'搜索PHP composer并自动加载。感谢Olaf Dietsche。我没有意识到此composer或自动加载有这么大的效果。但我仍然有一个问题。我不能不安装此PHP composer来使用此类库吗?是否有自定义方法来加载库而不安装composer?我不想在每个live se上安装此软件服务器和我的本地服务器只是为了使用这个库。还是我别无选择?当您以某种方式更改程序,然后它停止工作时,只需还原您的更改,看看它是否解决了问题。然后您可以查看相关代码,试着了解代码(或其缺失)如何影响您的程序。
require 'FastRoute/RouteCollector.php';
require 'FastRoute/Dispatcher.php';
...