首页 > 解决方案 > 无法使用 symfony 路由让路由在 php 应用程序中工作

问题描述

索引.php

require "vendor/autoload.php";
require "routes.php";

路由.php

<?php
require "vendor/autoload.php";

use Symfony\Component\Routing\Matcher\UrlMatcher;
use Symfony\Component\Routing\RequestContext;
use Symfony\Component\Routing\RouteCollection;
use Symfony\Component\Routing\Route;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Generator\UrlGenerator;
use Symfony\Component\Routing\Exception\ResourceNotFoundException;




try {

    $form_add_route = new Route(
        '/blog/add',
        array(
          'controller' => '\HAPBlog\Controller\EntityAddController',
          'method'=>'load'
        )
    );


    $routes = new RouteCollection();
    $routes->add('blog_add', $form_add_route);

    // Init RequestContext object
    $context = new RequestContext();
    $context->fromRequest(Request::createFromGlobals());

    $matcher = new UrlMatcher($routes, $context);
    $parameters = $matcher->match($context->getPathInfo());

    // How to generate a SEO URL
    $generator = new UrlGenerator($routes, $context);
    $url = $generator->generate('blog_add');
    echo $url;
}

catch (Exception $e) {
    echo '<pre>';
    print_r($e->getMessage());
}

src/Controller/EntityAddController.php

    <?php

namespace HAPBlog\Controller;

use Symfony\Component\HttpFoundation\Response;

class EntityAddController {

  public function load() {

      return new Response('ENTERS');

  }

}

我指的是下面给出的教程:

https://code.tutsplus.com/tutorials/set-up-routing-in-php-applications-using-the-symfony-routing-component--cms-31231

但是当我尝试访问该站点时http://example.com/routes.php/blog/add 它给出了一个空白页面。通过 PHPStorm 调试显示没有进入“EntityAddController”类 上面的代码有什么问题?

标签: phpsymfonyrouting

解决方案


这个过程没有什么神奇的,一旦你得到路由信息,你就必须调用配置的控制器并发送响应内容。

在这里举一个完整的例子:

// controllers.php

class BlogController
{
    public static function add(Request $request)
    {
        return new Response('Add page!');
    }
}

// routes.php

$routes = new RouteCollection();
$routes->add('blog_add', new Route('/blog/add', [
    'controller' => 'BlogController::add',
]));

// index.php

$request = Request::createFromGlobals();
$context = new RequestContext();
$context->fromRequest($request);
$matcher = new UrlMatcher($routes, $context);

try {
    $attributes = $matcher->match($request->getPathInfo());

    $response = $attributes['controller']($request);
} catch (ResourceNotFoundException $exception) {
    $response = new Response('Not Found', 404);
} catch (Exception $exception) {
    $response = new Response('An error occurred', 500);
}

$response->send();

推荐阅读