adrosoftware / lmrp-loader

Laminas Mezzio 辅助类,用于加载路由文件和管道。

v1.1.0 2021-08-30 01:04 UTC

This package is auto-updated.

Last update: 2024-08-29 05:50:15 UTC


README

Build status Coverage Status Latest Stable Version License

目的

在Laminas Mezzio上构建中型或大型应用程序时,最好能组织您的路由。默认情况下,mezzioconfig目录下的routes.php文件中定义了所有路由。对我来说,最好是至少按照路由前缀模块来组织路由。例如,routes.web.php用于所有Web路由,routes.api.php用于所有API路由。

使用方法

$ composer require adrosoftware/lmrp-loader

默认情况下,public/index.php文件看起来像这样

<?php

declare(strict_types=1);

// Delegate static file requests back to the PHP built-in webserver
if (PHP_SAPI === 'cli-server' && $_SERVER['SCRIPT_FILENAME'] !== __FILE__) {
    return false;
}

chdir(dirname(__DIR__));
require 'vendor/autoload.php';

/**
 * Self-called anonymous function that creates its own scope and keep the global namespace clean.
 */
(function () {
    /** @var \Psr\Container\ContainerInterface $container */
    $container = require 'config/container.php';

    /** @var \Mezzio\Application $app */
    $app = $container->get(\Mezzio\Application::class);
    $factory = $container->get(\Mezzio\MiddlewareFactory::class);

    // Execute programmatic/declarative middleware pipeline and routing
    // configuration statements
    (require 'config/pipeline.php')($app, $factory, $container);
    (require 'config/routes.php')($app, $factory, $container);

    $app->run();
})();

假设您有config/routes.web.phpconfig/routes.api.php等文件,然后替换为以下内容

(require 'config/routes.php')($app, $factory, $container);

例如,这样

(new \AdroSoftware\Lmrp\Loader('config/routes.*.php'))->load($app, $factory, $container);

为路由添加前缀。

从版本1.1开始,您现在可以使用文件的名称作为前缀来添加其中的路由。我们创建并注入了一个Prefixer类,在幕后使用\Mezzio\Application $app来生成路由。

例如,假设您有routes.web.phproutes.api.php,在您的index.php中,您使用prefix方法而不是load方法,如下所示

(new \AdroSoftware\Lmrp\Loader('config/routes.*.php'))->prefix($app, $factory, $container);

然后在您的routes.web.phproutes.api.php中,将匿名函数的定义从以下内容替换为

return static function (Application $app, MiddlewareFactory $factory, ContainerInterface $container): void

return static function (Application $app, MiddlewareFactory $factory, ContainerInterface $container, \AdroSoftware\Lmrp\Prefixer $prefixer = null): void 

现在您可以使用$prefixer而不是$app来创建路由

// `routes.api.php`
return static function (Application $app, MiddlewareFactory $factory, ContainerInterface $container, \AdroSoftware\Lmrp\Prefixer $prefixer = null): void {
    $app->get('/api/', Api\Handler\HomeHandler::class, 'api.home');
    // or
    $prefixer->get('/', Api\Handler\HomeHandler::class, 'api.home');
};

如您所见,您可以在所有路由中避免输入/api

注意:如果您不想将路由前缀为/api,则可以直接使用\Mezzio\Application $app

作者

Adro Rocker.