adrosoftware / lmrp-loader
Laminas Mezzio 辅助类,用于加载路由文件和管道。
v1.1.0
2021-08-30 01:04 UTC
Requires
- php: ^7.0
- laminas/laminas-stdlib: ^3.1.0
Requires (Dev)
- laminas/laminas-diactoros: ^2.6
- mezzio/mezzio: ^3.6
- phpunit/phpunit: ^9.0
This package is auto-updated.
Last update: 2024-08-29 05:50:15 UTC
README
目的
在Laminas Mezzio上构建中型或大型应用程序时,最好能组织您的路由。默认情况下,mezzio 在config
目录下的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.php
和config/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.php
和routes.api.php
,在您的index.php
中,您使用prefix
方法而不是load
方法,如下所示
(new \AdroSoftware\Lmrp\Loader('config/routes.*.php'))->prefix($app, $factory, $container);
然后在您的routes.web.php
和routes.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
。