安裝所需的包
composer require illuminate/routing
路由分發檔案 routes.php
<?php
use Illuminate\Http\RedirectResponse;
use Illuminate\Routing\Router;
$router->name('home')->get('/', function () {
return 'hello routes!';
});
$router->get('bye', function () {
return 'goodbye routes!';
});
$router->group(['namespace' => 'App\Controllers', 'prefix' => 'users'], function (Router $router) {
$router->get('/', ['name' => 'users.index', 'uses' => 'UsersController@index']);
$router->post('/', ['name' => 'users.store', 'uses' => 'UsersController@store']);
});
$router->get('/menu', function () use ($router) {
return new RedirectResponse($router->getRoutes()->getByName('home')->uri());
});
$router->any('{any}', function () {
return 'four oh four';
})->where('any', '(.*)');
專案入口檔案 index/routes.php
<?php
require_once __DIR__ . '/../vendor/autoload.php';
use Illuminate\Container\Container;
use Illuminate\Events\Dispatcher;
use Illuminate\Http\Request;
use Illuminate\Routing\Redirector;
use Illuminate\Routing\Router;
use Illuminate\Routing\UrlGenerator;
$container = new Container;
$request = Request::capture();
$container->instance('Illuminate\Http\Request', $request);
$events = new Dispatcher($container);
$router = new Router($events, $container);
require_once __DIR__ . '/../routes.php';
$redirect = new Redirector(new UrlGenerator($router->getRoutes(), $request));
$response = $router->dispatch($request);
$response->send();
控制器 src/Controllers/UsersController.php
<?php
namespace App\Controllers;
use Illuminate\Http\Request;
class UsersController
{
public function index()
{
return "
listing the users
<br>
<br>
<form method='post'>
<input type='text' name='name'>
<input type='submit'>
</form>";
}
public function store(Request $request)
{
$name = $request->input('name');
return "creating new user named $name";
}
}
命令列開啟服務 php -S localhost:8000
並訪問
http://localhost:8000/index/routes.php
http://localhost:8000/index/routes.php/bye
http://localhost:8000/index/routes.php/users
http://localhost:8000/index/routes.php/menu
http://localhost:8000/index/routes.php/anything
本作品採用《CC 協議》,轉載必須註明作者和本文連結