在Symfony PHP中生成友好的URL,可以使用URL重写和路由系统。以下是一些关键步骤:
config/routes.yaml
,并在其中定义路由规则。例如:app_homepage:
path: /
controller: App\Controller\HomeController::index
HomeController
中创建index
方法:namespace App\Controller;
use Symfony\Component\HttpFoundation\Response;
class HomeController
{
public function index()
{
return new Response('Hello, world!');
}
}
path
函数生成URL。例如,在templates/base.html.twig
中:<a href="{{ path('app_homepage') }}">Home</a>
.htaccess
文件中添加以下代码:<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php [QSA,L]
</IfModule>
public
目录下创建index.php
文件,并在其中引入Symfony框架。例如:<?php
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Debug\Debug;
use Symfony\Component\Dotenv\Dotenv;
require dirname(__DIR__).'/vendor/autoload.php';
(new Dotenv())->bootEnv(dirname(__DIR__).'/.env');
if ($_SERVER['APP_DEBUG']) {
umask(0000);
Debug::enable();
}
if ($trustedProxies = $_SERVER['TRUSTED_PROXIES'] ?? false) {
Request::setFactory(function (array $query = [], array $request = [], array $attributes = [], array $cookies = [], array $files = [], array $server = [], $content = null) use ($trustedProxies) {
$request = new Request($query, $request, $attributes, $cookies, $files, $server, $content);
$request->setTrustedProxies(explode(',', $trustedProxies), Request::HEADER_X_FORWARDED_ALL ^ Request::HEADER_X_FORWARDED_HOST);
return $request;
});
}
$kernel = new App\Kernel($_SERVER['APP_ENV'], (bool) $_SERVER['APP_DEBUG']);
$request = Request::createFromGlobals();
$response = $kernel->handle($request);
$response->send();
$kernel->terminate($request, $response);
通过以上步骤,您可以在Symfony PHP中生成友好的URL。推荐的腾讯云相关产品和产品介绍链接地址:
领取专属 10元无门槛券
手把手带您无忧上云