因此,我有几个带有mezzio框架的项目的子域():
我怎么才能在路线上使用呢?
此示例不起作用:
$app->get('journal.example.com', Journal\Handler\HomePageHandler::class, 'journal.home');发布于 2020-07-21 08:50:15
免责声明
这个答案解决了将请求路由到特定RequestHandler的子域的问题。但是,这并不是一个很好的实践,因为它带来了一些困难,比如路由配置中的开销和维护两个路由配置。此外,它不解决特定于子域的路径路由(例如http://journal.example.com/new或http://journal.example.com/list)。
跨不同子域使用相同的应用程序可能意味着会话处理等方面的挑战。对一个应用程序使用相同的域会使这些问题过时。
可能解决办法
由于路由不知道主机,所以路由配置中的简单解决方案是不可能的。它可以通过使用路由中间件来实现。
子域路由配置
在config/autoload/subdomain-routes.global.php中定义路由
<?php
declare(strict_types=1);
return [
'subdomain_routes' => [
'mezzio-subdomains.localhost' => \App\Handler\HomePageHandler::class,
'account.mezzio-subdomains.localhost' => \Account\Handler\HomepageHandler::class,
'journal.mezzio-subdomains.localhost' => \Journal\Handler\HomepageHandler::class,
],
];路由中间件
路由中间件使用SuperFactory src/App/Service/SuperFactory.php从容器中检索服务。
<?php
declare(strict_types=1);
namespace App\Service;
use Laminas\ServiceManager\Exception\ServiceNotFoundException;
use Psr\Container\ContainerInterface;
use Psr\Http\Server\RequestHandlerInterface;
class SuperFactory
{
private ContainerInterface $container;
public function __construct(ContainerInterface $container)
{
$this->container = $container;
}
public function create(string $serviceClass) : RequestHandlerInterface
{
if ($this->container->has($serviceClass)) {
return $this->container->get($serviceClass);
}
throw new ServiceNotFoundException(sprintf(
'Unable to resolve service "%s" to a factory; are you certain you provided it during configuration?',
$serviceClass
));
}
}如果找到匹配的子域,路由中间件src/App/Middleware/SubdomainRouter.php将返回RequestHandler的响应。
<?php
declare(strict_types=1);
namespace App\Middleware;
use App\Service\SuperFactory;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
class SubdomainRouter implements MiddlewareInterface
{
private array $subdomainRoutes;
private SuperFactory $superFactory;
public function __construct(array $subdomainRoutes, SuperFactory $superFactory)
{
$this->subdomainRoutes = $subdomainRoutes;
$this->superFactory = $superFactory;
}
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler) : ResponseInterface
{
$host = $request->getUri()->getHost();
if (array_key_exists($host, $this->subdomainRoutes)) {
$handler = $this->superFactory->create($this->subdomainRoutes[$host]);
return $handler->handle($request);
}
return $handler->handle($request);
}
}管道
路由中间件必须放在Mezzio\Router\Middleware\RouteMiddleware之前的管道中。
// [..]
// Add this line
$app->pipe(App\Middleware\SubdomainRouter::class);
// The following route is already defined in the skeleton
$app->pipe(RouteMiddleware::class);
// [..]完成
现在,对http://mezzio-subdomains.localhost/、http://account.mezzio-subdomains.localhost/和http://journal.mezzio-subdomains.localhost/的请求按配置进行路由。
https://stackoverflow.com/questions/61797674
复制相似问题