在非 laravel 專案中使用 laravel 的特性 7: 路由 routing

ZouZhipeng發表於2021-02-24

安裝所需的包

composer require illuminate/routing

路由分發檔案 routes.php

<?php

use Illuminate\Http\RedirectResponse;
use Illuminate\Routing\Router;

/** @var $router 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']);
});

// Redirect
$router->get('/menu', function () use ($router) {
    return new RedirectResponse($router->getRoutes()->getByName('home')->uri());
});

// catch-all route
$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;

// Create a service container
$container = new Container;

// Create a request from server variables, and bind it to the container; optional
$request = Request::capture();
$container->instance('Illuminate\Http\Request', $request);

// Using Illuminate/Events/Dispatcher here (not required); any implementation of
// Illuminate/Contracts/Event/Dispatcher is acceptable
$events = new Dispatcher($container);

// Create the router instance
$router = new Router($events, $container);

// Load the routes
require_once __DIR__ . '/../routes.php';

// Create the redirect instance
$redirect = new Redirector(new UrlGenerator($router->getRoutes(), $request));

// use redirect
// return $redirect->home();
// return $redirect->back();
// return $redirect->to('/');

// Dispatch the request through the router
$response = $router->dispatch($request);

// Send the response back to the browser
$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 協議》,轉載必須註明作者和本文連結

相關文章