我正在使用Symfony 2的网站上工作,其中每个用户都可以通过domain.com/username(与许多社交网站一样)访问个人资料页面.
为此,我需要检查用户选择一个URL时所需的URL是否可用.
我想知道Symfony中是否有一种方法可以获取路由配置中定义的路由使用的所有URL,以自动禁止这些路由作为用户名.
谢谢
解决方法:
现在我知道我有以application_frontend和application_backend开头的系统路由器.
app / config / routing.yml
application_frontend:
resource: "@ApplicationFrontendBundle/Controller"
prefix: /
type: annotation
application_backend:
resource: "@ApplicationBackendBundle/Controller"
prefix: /backend
type: annotation
我将控制器用作服务,但您不必这样做.
controller.yml
services:
application_frontend.controller.profile:
class: Application\FrontendBundle\Controller\ProfileController
arguments:
- @router
- @doctrine_common_inflector
doctrine_common_inflector:
class: Doctrine\Common\Inflector\Inflector
您应该重构爆炸位并进行一些清理,例如从路由名称中删除动作.我把它弄得有点脏,让您看看我在那儿到底在做什么.根据您的应用程序,此代码可能会更改.它只是给您一个想法,如何完成.
ProfileController
use Doctrine\Common\Inflector\Inflector;
use Symfony\Component\Routing\RouterInterface;
# .......
/**
* @Route("profile", service="application_frontend.controller.profile")
*/
class ProfileController extends Controller
{
private $router;
private $inflector;
public function __construct(
RouterInterface $router,
Inflector $inflector
) {
$this->router = $router;
$this->inflector = $inflector;
}
/**
* @Method({"GET"})
* @Route("/step_one")
*/
public function stepOneAction()
{
$list = [];
$myRoutes = ['application_frontend', 'application_backend'];
$routeCollection = $this->router->getRouteCollection();
foreach ($routeCollection->all() as $key => $value)
{
$data = $value->getDefaults();
if (isset($data['_controller'])) {
foreach ($myRoutes as $routePrefix) {
if (strstr($data['_controller'], $routePrefix) !== false) {
$routeParts = explode(':', $data['_controller']);
$routeParts2 = explode('.', $routeParts[0]);
$list[] = end($routeParts2). '/' . $this->inflector->tableize(end($routeParts));
}
}
}
}
echo '<pre>';
print_r($list);
exit;
}
}
您可以将列表与app / console debug:router命令进行比较.
结果
Array
(
[0] => country/index_action
[1] => country/list_action
[2] => default/index_action
[3] => default/list_action
[4] => profile/step_one_action
[5] => profile/step_two_action
[6] => profile/step_one_process_action
[7] => profile/step_two_process_action
[8] => security/index_action
[9] => security/login_action
[10] => security/logout_action
[11] => api/json_action
[12] => api/xml_action
[13] => api/json_xml_action
[14] => default/index_action
[15] => default/list_action
[16] => default/secret_action
[17] => superadmin/index_action
[18] => superadmin/list_action
[19] => twitter/list_action
[20] => twitter/create_tweet_action
[21] => user/list_action
[22] => user/create_action
)